More Basic Animation

Today I continued experimenting with the techniques I started using yesterday. I tried the exercise with filled circles and also after having placed additional objects on the screen. The only drawing modes that came close to supporting what I was trying to do had the undesirable side-effect of eliminating everything else on the canvas. That wasn’t going to work.

I did some more reading and decided on the brute force approach of just redrawing the entire screen for every refresh. That has the virtue of being bulletproof as far as getting exactly what you want displayed, but has the potential vices of being slow, causing flicker, and so on.

The process begins with clearing the canvas before drawing each frame. In theory one could use the context.clearRect function but that only works if you want a white background. If you want any other color you might as well use the context.fillRect function and get what you want. It appears to be pretty quick for areas of reasonable size. It’s also possible that only a portion of the canvas would need to be redrawn, and so only a portion would have to be cleared.

The next thing I noticed was that doing the animation using the setInterval function results in hiccups where the frame isn’t redrawn. This occurs at irregular intervals so I looked around some more and discovered the window.requestAnimationFrame function, which works most efficiently with the browser. As explained here, among other places, this preferred methodology has the advantages of automatically suspending when the canvas’s tab is hidden, syncs with other things the browser is doing, and works much more smoothly.

Here is the basic code. It looks like it’s making a recursive call but I interpret this instead as akin to placing the function call event in the browser’s refresh queue.

For today I’m stopping with this basic animation, which seems to work quite smoothly. It runs more quickly than yesterday’s experiment so I made the movement increments smaller. I’ll experiment with throttling the speed of the animation and stopping it outright tomorrow.

This entry was posted in Tools and methods and tagged , , . Bookmark the permalink.

Leave a Reply