<html>
<head>
<style type="text/css">
body {padding:0px;margin:0px;}
</style>
</head>
<body>
<canvas id="demo"></canvas>
<script>
//get the canvas element and create the 2d-drawing context
var c=document.getElementById('demo');
var cc=c.getContext("2d");
//this is where the animation is started.
//25ms is a good framerate for animations.
//the function "draw" (see below) will be executed each 25 milliseconds from now on.
var animation=setInterval(draw,25);
window.addEventListener("load",setDimensions);
window.addEventListener("resize",setDimensions);
//this function makes sure we'll always be using the entire width and
//height of a browser window, giving the animation somehow a
//responsive look and feel.
function setDimensions() {
c.width=window.innerWidth;
c.height=window.innerHeight;
};
//var x is a variable with a global scope. it can be accessed and changed in and outside functions
//in this case, x will increase every time the function draw() is executed, ie every 25 milliseconds
var x=0;
//this is the main function where you can program the animation.
function draw() {
//here the black rectangle will be drawn on the canvas
cc.clearRect(0,0,c.width,c.height);
cc.fillStyle="black";
cc.fillRect(x, 0, 50, 50);
//the rectangle moves from left to right, with steps of 3px
x+=3;
//its' good practice to stop an animation at some point,
//for instance when objects are out of sight - like in this example
//this animation stops when the rectangle is out of sight, ie when it reaches the
//right side of the browser window.
if (x > c.width) {
clearInterval(animation);
alert("Animation has stopped now!");
};
};
</script>
</body>
</html>