Skip to content Skip to sidebar Skip to footer

Prevent Canvas From Flickering On Redraw?

I am currently doing redraws like this: This works fine, except once in a while the character sprite will flash. This happens enough to be a pretty big annoyance. How should I do t

Solution 1:

Why you try to download background image each time when drawing background? Maybe next code is better:

var bg=null,ctxDrawInterval=-1;
init() {
  //stuff
  bg=new Image();
  bg.onload=function(){
    ctx.drawImage(bg,0,0,GAME_WIDTH,GAME_HEIGHT);
    ctxDrawInterval=setInterval(draw,100);
  }
  //bg.onerror=function(){
  //  what if error downloading?
  //}
  bg.src='img/background.png'; // must be placed after bg.onload
}

function draw() {
  drawBackground();
  character.draw(); //draws a sprite
}

function drawBackground() {
  ctx.drawImage(bg,0,0,GAME_WIDTH,GAME_HEIGHT);
}

Post a Comment for "Prevent Canvas From Flickering On Redraw?"