Nested Animation On Canvas

I wanted to explore the possibility of using animated butterflies on a site I was doing, so took the opportunity to try out some animation on Canvas using JavaScript. 

I started by taking a vector drawing of a butterfly (I simplified it by removing some points) and saving as a SVG so I could easily extract the points. I can then draw the butterfly onto the canvas. To create animation the canvas is redrawn on whatever interval you set, I’ve gone for 20 times a second. To simulate the butterfly’s wings flapping I’ve simply adjusted the horizontal scaling.

To add the butterflies onto the canvas I start by using, which keeps a record of the current state of the canvas (scale, rotation etc). I can then use context.translate(x,y) to shift the insertion point of the canvas before I add the butterfly, I aslo use context.rotate(r) to move the butterfly around in a circle. I can then use context.restore() to reset the canvas to the state it was in before placing the butterfly.

Obviously a butterfly going round in circles isn’t a great example of animation, but you could quite easily make it go in random directions or along a path with a few changes to the code. In the end I decided not to use canvas animation, as I wanted hundres of butterflies, which ends up killing the browser.

You can view the demo, and look at the source to see how I did it all.

Leave a Comment