simple canvas animation
bgCanvas for drawing background.
HTML
<span>CANVAS BASIC </span>
<div id="fps">0</div> fps
<canvas id="cv" width="500" height="460"></canvas>
CSS
body {background:#fe6;}
span { color:blue; font-family:Arial;float:left;}
div {float:left;}
canvas { border: 1px solid black; }
JavaScript
//Canvas dimensions.
var dimX=500;
var dimY=460;
var pos=null;
//Frames per second
var fps = 0, now, lastUpdate = (new Date)*1 - 1;
var fpsFilter = 50;
var fpsOut = document.getElementById('fps');
setInterval(function(){
fpsOut.innerHTML = fps.toFixed(1);}, 1000);
//BG canvas where we draw an static image.
var bg;
createBG_canvas();
function createBG_canvas(){
bg= document.createElement('canvas');
bg.width = dimX;
bg.height = dimY;
var ctx= bg.getContext('2d');
for(var i=0;i<dimX;i=i+30){
for(var j=0;j<dimY;j=j+20){
ctx.beginPath();
ctx.fillStyle =randomFillColor(i/dimX,j/dimY) ;
ctx.arc(i,j,25,0,2*Math.PI,true);
ctx.fill();
}
}
}
function randomFillColor(i,j){
return "rgb("+Math.round(i*255)+","+
Math.round(j*255)+","
+Math.round(0)+")";
}
//main context.
var ctx=document.getElementById("cv").getContext('2d');
//init render;
render();
//our render function
function render() {
requestAnimFrame(render);
animCanvas();
var thisFrameFPS = 1000 / ((now=new Date) - lastUpdate);
fps += (thisFrameFPS - fps) / fpsFilter;
lastUpdate = now * 1 - 1;
}
//anim canvas
function animCanvas(){
//ctx.clearRect(0,0,dimX,dimY);
drawBG();
pos=animPos();
ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.beginPath();
ctx.arc(pos.x, pos.y ,25,0,2*Math.PI,true);
ctx.fill();
}
function drawBG(){
if(pos==null)
ctx.drawImage(bg, 0, 0);
else{
var x=pos.x-25;
var y=pos.y-25;
x=Math.max(x,0);
y=Math.max(y,0);
x=Math.min(x,dimX-50);
y=Math.min(y,dimY-50);
ctx.drawImage(bg, x, y, 50, 50,
x, y, 50, 50);
}
}
function animPos(){
var date=new Date();
var inc=Math.round((date.getTime()/18)%dimX);
var y=Math.round(Math.cos(inc/40)*dimY*0.5);
return {x:inc,y:(dimY*0.5+y)};
}