I am trying to run an animate background with canvas. Right now the setTimeout shows an error in chrome Uncaught SyntaxError: Unexpected identifier. I must be animating it wrong.
When I remove setTimeout and just have the tiles(), everything works fine (i.e. not animated, but show the correct background that I want). So I am sure, it has something to do with setTimeout.
Anyone got clues for me?
function createBackground(){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
background = $('#game .background')[0],
rect = background.getBoundingClientRect(), //returns the dimension of background
gradient,
m = monster.settings.monsterSize;
canvas.width = rect.width;
canvas.height = rect.height;
/* create checker */
tile_cols = canvas.width / m;
tile_rows = canvas.height / m;
setTimeout(tiles(ctx, m, tile_cols, tile_rows), 300);
/* add canvas to html element */
background.appendChild(canvas);
}
function tiles(ctx, m, tile_cols, tile_rows){
for (var i=0; i<tile_cols; i++){
for (var j=0; j<tile_rows; j++){
var x = Math.ceil(Math.random()*3);
switch(x){
case 1:
ctx.fillStyle = 'black';
break;
....
case 3:
ctx.fillStyle = '#00080E';
break;
}
ctx.strokeStyle = 'black';
ctx.beginPath();
...
ctx.closePath();
ctx.fill();
ctx.stroke();
};
};
return this;
}
You’re assigning the result of
tiles(ctx, m, tile_cols, tile_rows)to the first parameter ofsetTimeoutChange it to
You should have a look at requestAnimationFrame for this task. Paul Irish wrote a good article about it.