Introduction
We all know about the growing demand of HTML5 Canvas. It is just being called a plug-in killer for the next generations of Web world. Anyway here I will show you how to create a simple linear animation with HTML5 canvas.
Before going to that I must describe what canvas is. Canvas is just an
HTML element which is used to draw things and do animation in browser itself with just
JavaScript .
To create an animation, we first need to initialize canvas and then set context too. Then with the help of
JavaScript we will draw a rectangle in side the canvas with context and we will repeatedly draw it by putting it inside a loop and clearing the previous drawn. So that finally it looks like an rectangle is moving from left to right. We will set the loop timer such that it will look smooth. Below is the
HTML code.
Using the code
<html>
<head>
<style type="text/css">
canvas{ border:#666 1px solid;}
</style>
<script type ="application/javascript" language="javascript">
function draw(x, y) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0, 0, 550, 400);
ctx.fillstyle = "rgba(0,200,0,1)";
ctx.fillRect(x, 20, 50, 50);
ctx.restore();
x+=1;
var loopTimer = setTimeout('draw('+x+','+y+')', 20);
}
</script>
</head>
<body>
<button onclick="draw(0,0)">Draw</button>
<canvas id = "canvas" width ="550" height ="400"></canvas>
</html>
Just copy and paste it in an HTML file and run it. Are you seeing it? Hope you enjoyed.