This article will tell you how to draw animations in Html5 canvas with examples.
1. How To Implement Animation Using Html5 Canvas Steps.
- Create a function ( function fun_a(){} ) that will draw the shape in Html5 canvas, for example, draw a rectangle.
- Call the javascript method setInterval(fun_a, time_interval) to execute the function fun_a periodically. The time_interval is the duration in milliseconds.
- For each time that executes the function fun_a, it will clear the canvas rectangle, then draw the rectangle with a new position and other attributes such as a different color.
2. Html5 Canvas Animation Example.
- When you click the Moving Square Animation button in this example, it will draw a red square that moves from left to right.
- When the red square reaches the right border, it will change color to green and move from right to left.
- When the green square reaches the left border, it will change color to red and move from left to right again.
- Below is the example demo image.
- You can see the demo video from URL https://youtu.be/8raZHsXOs74.
- This example contains 2 source files, html5-canvas-animation.html, html5-canvas-animation.js.
- html5-canvas-animation.html.
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Html5 Canvas Animation Examples</title> <script type="text/javascript" src="html5-canvas-animation.js" charset="utf-8"></script> <style> canvas{ display:block; margin-top:10px; } </style> </head> <body> <h3>Html5 Canvas Animation Examples.</h3> <div style="display:block;margin-top: 10px;"> <input type="button" value="Moving Square Animation" onclick="movingSquare('canvas1')" /> </div> <canvas id="canvas1"></canvas> </div> </body> </html>
- html5-canvas-animation.js.
var globalWidth = 600; var globalHeight = 300; var globalCtx; var startX = 0; var stepX = 10; var globalSquareColor = 'red'; function movingSquare(canvasId){ // Get the html canvas object. var canvas = document.getElementById(canvasId); if(canvas==null){ alert("Can not find the html element with element id " + canvasId); return false; } canvas.width = globalWidth; canvas.height = globalHeight; canvas.style.display = 'block'; canvas.style.backgroundColor = 'blue'; globalCtx = canvas.getContext('2d'); // execute the function moveAnimation in every 15 milliseconds. setInterval(moveAnimation, 15); } function moveAnimation(){ globalCtx.clearRect(0, 0, globalWidth, globalHeight); globalCtx.fillStyle = globalSquareColor; globalCtx.fillRect(startX,10,100,100); startX += stepX; if(startX >= globalWidth - 100){ stepX = 0 - stepX; globalSquareColor = 'green'; }else if(startX <= 0){ stepX = 10 globalSquareColor = 'red'; } }