Learn more about Russian war crimes in Ukraine.

Drawing a clock face with WebGL

Above you should see an analog clock face. The three hands move according to the current time. This is implemented with WebGL.

One piece of this is a vertex shader which converts 2D polar coordinates (convenient for drawing clock faces) into 3D cartesian coordinates in clip space (what OpenGL wants). The vertex shader is:

attribute vec2 polar_coord;
void main(void) {
  mediump float dist = polar_coord[0];
  mediump float ang = -polar_coord[1];
  mat2 rotate = mat2(cos(ang), sin(ang), -sin(ang), cos(ang));  // magic
  vec2 rotated = rotate * vec2(0.0, dist);
  gl_Position = vec4(rotated, 0.0, 1.0);

Once per second, the current time is converted to polar coordinates for the hands, which are passed to the vertex shader. The hands are drawn with gl.LINES, which draws one-pixel-wide lines. Here’s the JavaScript loop:

function toAngle(x, p) { return (x%p) * (2*Math.PI/p); }
  const now = new Date();
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
    0,0,  0.5,toAngle(now.getHours(),12),
    0,0,  0.7,toAngle(now.getMinutes(),60),
    0,0,  0.8,toAngle(now.getSeconds(),60),
  ]), gl.STATIC_DRAW);
  gl.drawArrays(gl.LINES, 0, 6);
}, 1000);

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged . All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.