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
timer_1 = setInterval(Timer_callback_function, 100); // calls the function every 100 milliseconds timer_2 = setTimeout(Another_function, 200); // calls the function once after 200 milliseconds clearInterval(timer_1); // stops the specified timer |
w3schools Examples
setInterval(drawClock, 1000); // used for the clock this.interval = setInterval(updateGameArea, 20); // used in the Default Gravity game |
In the Game Obstacles example, the following stops the timer.
start : function() { // setup code here this.interval = setInterval(updateGameArea, 20); }, stop : function() { clearInterval(this.interval); } |
setInterval vs setTimeout
setInterval(drawNextFrame, 1000); // 1000 ms = 1 second |
Object motions will look smooth if the screen is updated at 24 frames/sec or faster.
setInterval(drawNextFrame, 1000/24); // 24 frames/sec |
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
// define the global variables here, outside all the functions function Graph_setup() { // set the global variables here window.setTimeout(Graph_Update_loop, 1); } function Graph_Update_loop() { // draw new image here count += 1 ; // this is used to know which frame to draw if (count <= stop){ window.setTimeout(Graph_Update_loop, 1); } else { window.setTimeout(Graph_Update_complete, 1); } // the new image is shown when this function terminates } function Graph_Update_complete() { // This executes after the animation is complete // to repeat the animation, simply call Graph_setup } |
requestAnimationFrame
This is all w3schools says about it.
"Requests the browser to call a function to update an animation before the next repaint" |
Other techniques
As a result, you will have to use one of the timer-based techniques described above to animate an image.
Author: Robert Clemenzi