Since Flex is Dead, I decided to rebuild my fancy Flex Clock using the html5 canvas element. Here is the result:

(click to see it in action)

Lots of very vanilla drawing code that is fairly boring, but one interesting part is how the new canvas-based clock uses svg paths. The old flex code used svg paths liberally as simple way to draw shapes, but since canvas doesn’t support drawing svg path data directly I had to write my own:

function drawPath(ctx,path,fill,ang) {;
    ctx.rotate(ang == undefined ? 0 : ang  * Math.PI / 180.0);
    var parts = path.split(' ');
    while (parts.length > 0) {
        var part = parts.shift();
        if (part == 'M') {
            coords = parts.shift().split(',');
            ctx.moveTo(coords[0], coords[1]);
        } else if (part == 'L') {
        } else if (part == 'Z') {
        } else if (part.indexOf(',') >= 0) {
            coords = part.split(',');
            ctx.lineTo(coords[0], coords[1]);
    ctx.fillStyle = (fill == undefined ? '#000' : fill);

The drawPath() function takes svg path data as input (with the restriction that it contains only M (move to), L (line to), and Z (close path) elements), and executes moveTo() and lineTo() calls in the canvas element instead. It does zero error checking, so the incoming svg path data must be well formatted.

If you call it like this:

drawPath(ctx, 'M 0,0 L 0,10 10,10 10,0 Z');

You’d get a nice 10px by 10px square as expected.


It’s no surprise that canvas is just as powerful as Flex or SVG as far as drawing shapes and gradients, but it would definitely make canvas extra cool if it had more intergrated svg path support. Yes, of course, I could have used pure svg if I wanted to draw a bunch of svg shapes, but I had set my mind on using canvas only.


© 2017