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); }
window.setInterval(function(){
  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.clear(gl.COLOR_BUFFER_BIT);
  gl.drawArrays(gl.LINES, 0, 6);
}, 1000);
Tagged #webgl, #javascript, #web, #clock, #animation, #graphics-programming.
đź‘‹ I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

More by Jim

This page copyright James Fisher 2017. Content is not associated with my employer. Found an error? Edit this page.