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. save ( ) ; ctx. rotate ( ang == undefined ? 0 : ang * Math. PI / 180.0 ) ; ctx. beginPath ( ) ; 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' ) { continue ; } else if ( part == 'Z' ) { break ; } else if ( part. indexOf ( ',' ) >= 0 ) { coords = part. split ( ',' ) ; ctx. lineTo ( coords [ 0 ] , coords [ 1 ] ) ; } } ctx. closePath ( ) ; ctx. fillStyle = ( fill == undefined ? '#000' : fill ) ; ctx. fill ( ) ; ctx. restore ( ) ; }

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.

Conclusion

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.

Files