我目前正在进行这样的重绘:
这个工作正常,除了偶尔字符精灵会闪烁。这恰好是一个非常大的烦恼。我该如何更有效地做到这一点?我也试过改变重绘频率。较高的频率加剧了问题,而较低的频率由于图形原因不够快。
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);
}
答案 0 :(得分:2)
为什么每次绘制背景时都尝试下载背景图像?也许下一个代码更好:
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);
}