In previous sections, we have already learnt about HTML5 Canvas, so here our focus would be to create a simple Animation on HTML5 Canvas by calling strokeRect and clearRect methods of Canvas element using JavaScript.
Output
Below is the HTML and JavaScript both code snippets, simply copy-paste into a blank HTML5 under <body> element and our animation is ready.
<canvas id="Canvas1" width="400" height="400" style="border:1px solid green;">
Canvas is not supported in your browser
</canvas>
<script type="text/javascript">
var canvas;
var context;
var x = 50;
var y = 60;
var timer;
function StartAnimation() {
canvas = document.getElementById("Canvas1");
context = canvas.getContext("2d");
timer = setInterval(AnimateNow, 10);
}
function AnimateNow() {
x++;
y++;
context.strokeStyle = "green";
context.strokeRect(x, y, 100, 100);
if (y == canvas.height) {
x = 50;
y = 60;
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
StartAnimation();
</script>
In above code snippet, we have create few global variables that will hold the canvas, context, x co-ordinates, y co-ordinates and setInterval values.
setInterval() function of JavaScript is used to call a user defined function after certain time interva, this function also returns a handle (in this case the handler is stored into timer variable) that can be used to stop the execution of repeatative function (with the help of clearInterval() function).
When the page loads, StartAnimation() function is called that sets the HTML5 canvas object into canvas
variables and its context into context
variable. After that the timer
(setInterval) starts that keep executing AnimateNow function after every 10 seconds.
In AnimateNow function, we increase the x and y variable values to 1 and draw the rectangle on canvas using strokeRect method after specifying the strokeStyle (border of the rectangle).
If the height of the rectangle reaches to the height of the canvas, we reset the x and y co-ordinates value and clear the canvas by calling clearRect() method on context.
Views: 9371 | Post Order: 112