Canvas Draw with caching

by kzhdev

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    smiley = {};

canvas.width = canvas.height = 500;

smiley.x = 50;
smiley.y = 50;

// cach the smiley
var canvasTemp = document.createElement("canvas"),
    tCtx = canvasTemp.getContext("2d");

canvasTemp.width = canvasTemp.height = 150;

tCtx.fillStyle = "#FFA812";
tCtx.beginPath();
tCtx.arc(75,75,30,0,Math.PI*2,true); // Outer circle
tCtx.fill();
tCtx.closePath();

tCtx.beginPath();
tCtx.moveTo(110,75);
tCtx.arc(75,75,25,0,Math.PI,false);   // Mouth
tCtx.closePath();
tCtx.fillStyle = "#000";
tCtx.fill();

tCtx.beginPath();
tCtx.moveTo(65,65);
tCtx.arc(60,65,5,0,Math.PI*1.5,true);  // Left eye
tCtx.moveTo(95,65);
tCtx.arc(90,65,5,0,Math.PI*1.7,true);  // Right eye 
tCtx.closePath();
tCtx.fill();

function update() {
    //ctx.clearRect(0,0,500,500);
    var x = smiley.x++,
        y = smiley.y++;
        
    if( x>450) {
        smiley.x=0;
    }
        
    if( y>450) {
        smiley.y=0;
    }
    
    ctx.clearRect(x, y, 150, 150);
    ctx.drawImage(tCtx.canvas, x, y);

    setTimeout(update,1000);
}

update();