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开发者_JAVA百科 ()
{
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);
}
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);
}
精彩评论