我正在尝试在画布上运行带有图像的动画,但是当我运行代码时出现错误:
未捕获的DOMException:无法在“ CanvasRenderingContext2D”上执行“ drawImage”:提供的HTMLImageElement处于“损坏”状态。
代码如下:
let canvasWidth = 400;
let canvasHeight = 550;
let spriteWidth = 500;
let spriteHeight = 250;
let rows = 1;
let cols = 2;
let width = spriteWidth / cols;
let height = spriteHeight / rows;
let curFrame = 0;
let frameCount = 2;
let x = 0;
let y = -100;
let srcX;
let srcY;
let right = true;
let speed = -12;
let canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
let ctx = canvas.getContext("2d");
let character = new Image();
character.src = "image.png";
function updateFrame() {
curFrame = ++curFrame % frameCount;
srcX = curFrame * width;
ctx.clearRect(x, y, width, height);
srcY = 0 * height;
y -= speed;
}
function draw() {
updateFrame();
ctx.drawImage(character, srcX, srcY, width, height, x, y, width, height);
}
setInterval(draw, 500);