我为我的游戏循环实现了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
但是我得到这个错误:
未捕获的TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(CSSImageValue或HTMLImageElement或SVGImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型
它指向以下代码行:
ctx.drawImage(images[this.spriteCostumeCount], this.x, this.y, this.width, this.height);
在图形代码中。
如何使用此requestAnimationFrame获取要播放动画的播放器精灵,如何解决此错误?
最佳答案
您需要确保定义了images[this.spriteCostumeCount]
并具有正确的类型。
一种简单的测试方法是在调用console.log(typeof images[this.spriteCostumeCount])
方法之前添加drawImage
。
如果结果不确定,则可以将呼叫封装为if
条件。如果已定义,则将其设置为drawImage
方法可接受的类型。
关于javascript - 无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57326172/