0

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 this more efficiently? I also tried changing the redraw frequency. Higher frequencies exacerbated the problem while lower frequencies are not fast enough for graphical reasons.

init()
{
//stuff
    return setInterval(draw,100);
}

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

//this function is called when character is created
Character.prototype.setImage = function ()
{
    this.avatar= new Image();
    this.avatar.onload=function(){
            this.imageLoaded=true;
    };
    this.avatar.src='/img/sprite.png';
}

Character.prototype.draw=function(ctx)
{  
    var imageW=this.imageW;
    var imageH=this.imageH;

    ctx.drawImage(avatar,20,20,imageW,imageH);

}
Razor Storm
  • 12,167
  • 20
  • 88
  • 148
  • I tried, but JSFiddle doesn't seem to like object orientation and it is giving random errors: http://jsfiddle.net/2Gkws/16/ – Razor Storm Sep 21 '11 at 08:40

1 Answers1

2

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);
}
Andrew D.
  • 8,130
  • 3
  • 21
  • 23
  • When i tried that for the character sprite (you can see the code in the bottom portion of my original question), it flickered even more. I can't set the interval for my character's drawing in `onload` because it needs to be synchronized with a global timer. – Razor Storm Sep 21 '11 at 08:20
  • Basic idea is to preload all images (background, character sprites) before usage. And, when download of all images finished - start an animation. – Andrew D. Sep 21 '11 at 08:27