【问题标题】:Error in loading drawImage() method in Javascript canvas在 Javascript 画布中加载 drawImage() 方法时出错
【发布时间】:2022-01-05 07:59:15
【问题描述】:

我的代码中有以下类:

//Collectables
const humanImg = new Image();
humanImg.src = "../images/human.png";
const mutationImg = new Image();
mutationImg.src = "../images/mutation.png";
//Canvas
const mycanvas = document.getElementById('my-canvas');
let ctx = mycanvas.getContext('2d');
//Classes
class Collectable {
    constructor(img, x, y, width, height) {
        this.img = img;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.collected = false;
        this.notScored = true;
        this.mutate = false;
    };
    draw(){
        ctx.drawImage(this.img, this.x, this.y, this.width, this.height);
    };
    checkcollision(object) {
        return (
          this.x < object.x + object.width &&
          this.x + this.width > object.x &&
          this.y < object.y + object.height &&
          this.y + this.height > object.y
        );
    };
    collect(object){
        if (this.checkcollision(object)) {
            this.collected = true;
            ctx.clearRect(this.x, this.y, this.width, this.height);
            ctx.fillStyle = "black";
            ctx.fillRect(this.x, this.y, this.width, this.height);
            this.mutate = true;
        };
    };
    updateScore(object, score){
        if ((this.checkcollision(object)) && (this.notScored === true)){
            points += score;
            pointsRestart += score;
            this.notScored = false;
            playerMovingAudio.play();
            playerMovingAudio.volume = 0.6;
        };
    };
};

稍后当我调用Collectable类时的代码:

// Collectables
const specialCollects = [
    new Collectable(mutationImg, 20, 60, 30, 30),
    new Collectable(mutationImg, 950, 60, 30, 30),
    new Collectable(mutationImg, 20, 500, 30, 30),
    new Collectable(mutationImg, 950, 500, 30, 30)
];

我收到一个错误:

Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.

而且我也不知道怎么解决,错误就在这一行:

ctx.drawImage(this.img, this.x, this.y, this.width, this.height);

在Collectable 类中。我试图在该行添加和 onload 事件,但错误仍然存​​在。我能做什么?

谢谢!

【问题讨论】:

    标签: javascript canvas html5-canvas onload drawimage


    【解决方案1】:

    最后我解决了这个问题,将 js 文件更改为根目录。我认为查找图像需要时间,因为它必须在两个文件夹之间查找,我之前将 js 文件放在一个名为 \js 的文件夹中。所以谢谢你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 2011-05-10
      • 2013-08-10
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多