# 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 wrote this because I felt like it. This post is not associated with my employer. This site is hosted by Netlify (who are great, but I'm not associated with them either).