Simple Animation using Canvas: HTML5


Today lets see how we can do simple animation using Canvas.

moving-circle-animation-canvas-html5

Demo

Here we draw a circle and move it from starting point of x-axis to the end of the canvas.

index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5

JavaScript file: Moving Circle Code
myScript.js

1
2
3
4
context.beginPath();
context.fillStyle = "red";
context.arc(x++, context.canvas.height/2, r, 0, 2 * Math.PI);
context.fill();

Here I’m drawing a circle with a red fill and incrementing it’s x-axis value each time it is called.

JavaScript file: x-axis movement control
myScript.js

1
2
3
4
5
var r = 50;
var x = -r;
 
if( x >= context.canvas.width + r)
    x  = -r;

Here the x-axis value is tracked each time and is set back to -50 ( minus radius of the circle ) once the circle moves out of the x-axis or the canvas width.

Simple Animation using Canvas: HTML5



YouTube Link: https://www.youtube.com/watch?v=iyGQhumPgcc [Watch the Video In Full Screen.]



JavaScript file: Full Free Source Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
window.onload = canvas;
 
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
 
if( myCanvas && myCanvas.getContext("2d") ) 
{
var context         = myCanvas.getContext("2d");
var r = 50;
var x = -r;
 
setInterval(function(){
context.fillStyle   = "#000";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
 
context.beginPath();
context.fillStyle   = "red";
context.arc(x++, context.canvas.height/2, r, 0, 2 * Math.PI);
context.fill();
 
if( x >= context.canvas.width + r)
    x  = -r; 
}, 10);
}
}

Here we use the setInterval() method to iterate/loop through the anonymous function and each time the background of the canvas is set to black(#000 or #000000) by drawing a black rectangle across the entire canvas width and height. For every call the value of x increments by 1, hence the circle moves 1px away from its previous position, until it reaches the end of canvas – after which it is reset back to -r value.

Leave a Reply

Your email address will not be published. Required fields are marked *