【发布时间】: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