xxxxxxxxxx
111
/*
Display the current time in a classic format.
Demonstrates:
Getting the current time in H:M:S:ms from the JS Date Object
Converting those values to hand positions, taking into account fractional positions between markers
Code-driven mark making for the chapter ring
Derriving proportions from the overall diameter of the clock rather than hard coding pixel values
*/
let d = 800, //main diameter
r = d/2, //radius
h = d + 20,
w = h,
h2 = h/2,
w2 = w/2;
let now = new Date();
function setup() {
frameRate(60);
createCanvas(w, h);
}
function draw() {
background(32);
now = new Date();
push(); //we'll work with matrix translations and rotations so that 0,0 is centered and 0 degrees is at 12 o'clock
translate(h2, w2);
rotate(-PI/2);
ellipse(0, 0, d, d);
//Hour and minute marks
push();
stroke(0);
let steps = 60,
stepAngle = TWO_PI/steps;
let innerR = 0.85*r,
outerR = 0.95*r;
//ellipse();
for (let i=0; i <steps; i++) {
if (i%5==0) strokeWeight(5);
else strokeWeight(1);
if (i==0) strokeWeight(10);
line(innerR,0,outerR,0);
rotate(stepAngle);
}
pop();
//Hands
let hoursR = innerR * 0.75;
let jumpingHours = false;
let hoursAngle = (now.getHours() % 12) * TWO_PI/12;
if (!jumpingHours) {
hoursAngle += (TWO_PI/12) * (now.getMinutes() / 60.0);
}
push();
stroke(32);
fill(32);
strokeWeight(25);
rotate(hoursAngle);
line(0,0,hoursR, 0);
pop();
//Minutes
let minutesR = innerR * 0.95;
let jumpingMinutes = false; //jumping minutes - that transition suddenly from one minute to the next, are rare in mechanical watches
let minutesAngle = now.getMinutes() * TWO_PI/60;
if (!jumpingMinutes) {
minutesAngle += (TWO_PI/60) * (now.getSeconds() / 60.0);
}
push();
stroke(0);
fill(0);
strokeWeight(10);
ellipse(0,0,30,30);
rotate(minutesAngle);
line(0,0,minutesR, 0);
pop();
//Seconds
let secondsR = outerR;
let sweepSeconds = true; //Sweeping seconds that move smoothly between seconds are common on mechanical watches. Inverse of jumping
let secondsAngle = now.getSeconds() * TWO_PI/60;
if (sweepSeconds) { //add angle based on millis
secondsAngle += (TWO_PI/60) * (now.getMilliseconds()/1000.0);
}
push();
stroke(255, 0, 0);
fill(255, 0, 0);
strokeWeight(4);
ellipse(0,0,20,20);
rotate(secondsAngle);
line(-20, 0, secondsR, 0);
pop();
pop(); //End main dial transform
noStroke();
fill(255);
text(timeString(now), 20, 20);
}
function timeString(d) {
return d.getHours() + ":" +
nf(d.getMinutes(), 2, 0) + ":" +
nf(d.getSeconds(), 2, 0) + ":" +
nf(d.getMilliseconds(), 3, 0);
}