How to Draw a Clock with SVG and JavaScript
Generating images with central symmetry is one of the many use cases of rotating image elements. In this example, we create a clock that shows the actual time. We draw the clock with SVG and use JavaScript to turn the hour and minute handles in the right direction.
How to Rotate and Translate SVG ElementsSVG elements can be manipulated from JavaScript the same way as any other HTML element. In this example, we are using a short code snipped to show the actual time on a clock. We access the hour and minute hands in JavaScript with getElementById
then set their transform
attribute with a rotation that reflects the current time.
There’s another trick here worth mentioning. The dots here showing each hour are drawn as a dashed circle. This works similarly as we can set the border-style
CSS property for regular HTML elements, but more sophisticated. In SVG we can fine-tune the length of each dash segment and the space in between with the stroke-dasharray
property. We can also set an offset with stroke-dashoffset
.
You can find a more detailed explanation of a similar clock in this YouTube tutorial.