Javascript examples for Canvas:Animation
Canvas: animating a simple star field
<!doctype html> <html> <head> <!-- reset css --> <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> <style> #container{/*from w w w.ja v a 2s. com*/ position:relative; border:1px solid blue; width:300px; height:300px; } .subcanvs{ position:absolute; } </style> <script> $(function(){ window.requestAnimFrame = (function(callback) { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var background=document.getElementById("background"); var bkCtx=background.getContext("2d"); var backImage=RandomStarsImage(); ctx.beginPath(); ctx.fillStyle="red"; ctx.rect(75,100,100,50); ctx.arc(175,125,25,0,Math.PI*2,false); ctx.closePath(); ctx.fill(); var fps = 60; var offsetLeft=0; panStars(); function panStars() { offsetLeft+=1; if(offsetLeft>backImage.width){ offsetLeft=0; } bkCtx.clearRect(0,0,background.width,background.height); bkCtx.drawImage(backImage,-offsetLeft,0); bkCtx.drawImage(backImage,backImage.width-offsetLeft,0); setTimeout(function() { requestAnimFrame(panStars); }, 1000 / fps); } function RandomStarsImage(){ bkCtx.beginPath(); bkCtx.fillStyle="darkblue"; bkCtx.rect(0,0,background.width,background.height); bkCtx.fill(); bkCtx.beginPath(); for(var n=0;n<100;n++){ var x=parseInt(Math.random()*canvas.width); var y=parseInt(Math.random()*canvas.height); var radius=Math.random()*3; bkCtx.arc(x,y,radius,0,Math.PI*2,false); bkCtx.closePath(); } bkCtx.fillStyle="white"; bkCtx.fill(); var img=document.createElement("img"); img.src=background.toDataURL(); return(img); } }); // end $(function(){}); </script> </head> <body> <div id="container"> <canvas id="background" class="subcanvs" width="300;" height="300;"></canvas> <canvas id="canvas" class="subcanvs" width="300;" height="300;"></canvas> </div> </body> </html>