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);
I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

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