Skip to content

Instantly share code, notes, and snippets.

@jgrahamc
Last active June 3, 2019 17:06
Show Gist options
  • Save jgrahamc/20bcd1fc1e102ad19a1a7760c9efae7d to your computer and use it in GitHub Desktop.
Save jgrahamc/20bcd1fc1e102ad19a1a7760c9efae7d to your computer and use it in GitHub Desktop.
// Draw all clock faces where the hands are symmetrically placed either side of the
// vertical 12<->6 line
void setup() {
size(720, 480);
// r is each clock's radius
// f is a fudge factor used to make space between the clocks
int r = 50;
int f = 10;
textSize(10);
textAlign(CENTER);
for (int h = 0; h <= 12; h++) {
float m = (360-30*float(h))*2/13;
int s = round(60 * (m - floor(m)));
int col = h%6;
int row = floor(h/6);
draw_clock((r+f)*(2*col+1), (r+f)*(row*2+1), r, h, floor(m), s);
}
}
// draw_clock draws a clock at (x, y) of radius r showing the time
// h:m.s
void draw_clock(int x, int y, int r, int h, int m, int s) {
ellipse(x, y, r*2, r*2);
ellipse(x, y, 2, 2);
for (float t = 0; t < 2 * PI; t += 2 * PI/12) {
ellipse(x+r*cos(t), y+r*sin(t), 2, 2);
}
// Hour hand angle (parens here are unnecessary but used to indicate how
// to think about the calculation
float ht = ((2 * PI)/12)*h;
ht += (((2 * PI)/12)*m)/60;
ht += (((2 * PI)/60)*s)/60/12;
draw_hand(x, y, r * 0.6, ht);
// Minute hand angle
float mt = ((2 * PI)/60)*m;
mt += (((2 * PI)/60)*s)/60;
draw_hand(x, y, r * 0.8, mt);
String hms = nf(h, 2) + ":" + nf(m, 2) + "." + nf(s, 2);
fill(0);
if ((m < 15) || (m > 45)) {
y += 15;
} else {
y -= 5;
}
text(hms, x, y);
fill(255);
}
// draw_hand draws one of the clock hands centered on (x, y),
// with length r and angle t.
void draw_hand(int x, int y, float r, float t) {
t -= 2*PI/4; // Adjust since we want t == 0 to be vertical
line(x, y, x+r*cos(t), y+r*sin(t));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment