Javascript - Graph Animation

Another page explains the basics of creating a graph - this page explains how to animate a graph.

In principle, animation is simply showing one graph (one frame) after another. Unfortunately, the technique to show the new image is compiler/interpreter dependent.

In general, you want to draw the new image off screen and then switch to it.

With javascript, changes to the canvas are not displayed until all your code completes. This means that you can not write a loop to animate the image. Instead, you must use a timer to call an update function.

Timers | w3schools Examples | setInterval vs setTimeout | requestAnimationFramerequestAnimationFrame | Other techniques


Timers

The Javascript timer components can be configured Both functions For additional notes on timers, and how to solve some specific problems, see - Understanding timers: setTimeout and setInterval


w3schools Examples

w3schools provides two examples on how to animate (update) an image on a canvas. In both cases, the technique that makes it happen is based on using a timer. In both cases, the timer runs forever - which is appropriate for the clock, but not for the game.

In the Game Obstacles example, the following stops the timer.

Far more complex examples are provided in this Animation Tutorial.


setInterval vs setTimeout

If you want something slow and regular, like a clock, then setInterval is the logical choice. For instance, in the Clock Example, the update function is called once per second via

Object motions will look smooth if the screen is updated at 24 frames/sec or faster.

However, for some animations, the maximum update speed is dependent on the speed of the code. In those cases, you want to make sure that

In that case, I prefer to use setTimeout (with a timeout value of only one millisecond) and to call it each time the image is created, as shown below. The following example runs for a fixed number of steps and then quits.


requestAnimationFrame

window.requestAnimationFrame(callbackFunction) instructs the browser to call the callbackFunction before the next window repaint - about 60 times a second.

This is all w3schools says about it.


Other techniques

Numerous comments state that javascript code can force a screen refresh by changing (or simply reading) various style parameters. I tried many suggestions - none worked. It is possible that those techniques work for some html components, but I never got them to work with canvas.

As a result, you will have to use one of the timer-based techniques described above to animate an image.


Author: Robert Clemenzi
URL: http:// mc-computing.com / Languages / Javascript / Graph_Animation.html