【问题标题】:Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的值不是“类型”
【发布时间】: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


【解决方案1】:

您需要确保 images[this.spriteCostumeCount] 已定义且类型正确。

一个简单的测试方法是在调用drawImage 方法之前添加一个console.log(typeof images[this.spriteCostumeCount])

如果结果未定义,您可以将调用封装在if 条件中。如果已定义,则使其成为drawImage 方法接受的类型。

【讨论】:

  • 是的,由于某种原因它是未定义的。我究竟应该封装什么?
  • 另外,我记录了整个数组。它显示为“img”对象的数组
  • 我现在正在使用手机,但也许可以尝试使用示例部分中developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement 中描述的 createElement 方法创建一个 HTMLImageElement。
猜你喜欢
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2015-05-07
  • 1970-01-01
  • 2018-11-29
相关资源
最近更新 更多