【发布时间】:2019-12-11 01:31:25
【问题描述】:
我已经为我的游戏循环实现了一个 rAF(requestAnimationFrame) 设置:
draw: function (x, y) {
setTimeout(function () {
requestAnimationFrame(function() {
Player.draw(150, 150);
});
//drawing code: worked perfectly with setInterval
}, 1000 / 60);
},
它在 Player 对象中,在 draw 函数中。我打电话:
Player.draw(Player.x, Player.y);
在代码的底部。
根据我在类似问题上看到的情况,需要在评估之前声明图像。我已使用立即调用的函数将图像加载到顶部:
var images = [];
x = 0;
(function() {
for (let i = 0; i < 20; i++) {
images[i] = new Image();
images[i].src = ('../webgame/assets/images/survivor-idle_shotgun_' + i + '.png');
};
})(); // This worked perfectly with setInterval too
但是我得到了这个错误:
未捕获的类型错误:无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的值不是类型“(CSSImageValue 或 HTMLImageElement 或 SVGImageElement 或 HTMLVideoElement 或 HTMLCanvasElement 或 ImageBitmap 或 OffscreenCanvas)”
它指向这行代码:
ctx.drawImage(images[this.spriteCostumeCount], this.x, this.y, this.width, this.height);
在绘图代码中。
如何使用此 requestAnimationFrame 为玩家精灵设置动画,如何解决此错误?
【问题讨论】:
-
你能不能在出现错误的那一行前加一个
console.log(images[this.spriteCostumeCount]),这样你就可以看到它的类型和属性了吗?
标签: javascript