In my previous post I drew a heart shape using the HTML5 canvas. After that I tried my hand at simple animation by making the heart move within constrained boundaries.
After reading quite a bit on Google, the suggested way to animate a shape on a canvas seems to be do continuously keep redrawing the canvas and clearing it. When done on a short enough interval, this gives the illusion of animation. Though I’m not sure of the performance implications of this approach, it works quite well in simpler animation scenarios.
One more thing to change from the previous post is that I had hardcoded all the coordinates for the shape. With continuously changing coordinates in animation, this was no longer possible. So I modified the code to take a reference point X,Y and draw the shape relative to it. For the animation logic these X,Y (which are global variables) are added/ subtracted by smaller values (dx,dy) repeatedly. Since every time the image is drawn relative to reference points we are able to use the same code.
The code is below .