NextIndexPrevious

Programs in HTML5

11. Animation using Canvas.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
	<canvas id="myCanvas" width="600" height="400" style="border-color:#63F; 
    border-style:solid">
    </canvas>
    <script>
    	var c = document.getElementById("myCanvas");
		var ctx = c.getContext('2d');
		var x=0;
		function draw()
		{
			x=x+10;
			if(x==400) clearInterval(n);
			ctx.save();
			ctx.clearRect(0,0,600,500);
	
			if(x<100)
			ctx.fillStyle = "green";
			else if(x<200)
				 ctx.fillStyle = "blue";
				 else if(x<300)
			 			ctx.fillStyle = "red";
					  else
					    ctx.fillStyle = "black";
		 	
			ctx.beginPath();
			ctx.arc(100+x,200,50,0,(2*Math.PI));
			ctx.closePath();
			ctx.fill();
		}

		var n = setInterval(function(){draw()},100);

	</script>
</body>
</html>


Output :





Developed by


World Wide Web Consortium WHATWG

World Wide Web Consortium & WHATWG