我有画布的问题,我正在尝试绘制图像但是没有工作,因为你可以看到我正在将图像加载到数组中并等待所有加载后我每次迭代都会更改我的图像但不是绘制任何一个,请查看我的代码。我找不到错误:(
(() => {
"use strict";
const images = [];
const promises = [];
const url = './assets/';
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const FPS = 30;
const INTERVAL = 10000 / FPS;
const canvasDraw = () => {
let i = 0;
setInterval(() => {
context.drawImage(images[i] , 300, 300);
i++;
if (i === images.length) i = 0;
}, INTERVAL);
};
const loadImage = (image) => {
return new Promise((resolve) => {
const img = new Image();
img.src = url + image + '.png';
img.onload = function () {
images.push(img);
resolve();
};
});
};
for(let i = 1; i < 14; i++) {
promises.push(loadImage(i));
}
Promise
.all(promises)
.then(() => {
canvasDraw();
});
})();
我的html文件包含像这样的画布
<canvas id="canvas"></canvas>
答案 0 :(得分:2)
您需要为画布指定宽度和高度。
使用占位符图片:
(() => {
"use strict";
const images = [];
const promises = [];
const url = './assets/';
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const FPS = 30;
const INTERVAL = 10000 / FPS;
const canvasDraw = () => {
let i = 0;
setInterval(() => {
context.drawImage(images[i] , 0, 0);
i++;
if (i === images.length) i = 0;
}, INTERVAL);
};
const loadImage = (image) => {
return new Promise((resolve) => {
const img = new Image();
img.src = 'https://placehold.it/' + (image * 20) + 'x' + (image * 20);
img.onload = function () {
images.push(img);
resolve();
};
});
};
for(let i = 1; i < 14; i++) {
promises.push(loadImage(i));
}
Promise
.all(promises)
.then(() => {
canvasDraw();
});
})();
&#13;
<canvas id="canvas" width="300" height="300"></canvas>
&#13;
根据您正在做的事情,您可能希望在渲染之间清除画布。
(() => {
"use strict";
const images = [];
const promises = [];
const url = './assets/';
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const FPS = 30;
const INTERVAL = 10000 / FPS;
const canvasDraw = () => {
let i = 0;
setInterval(() => {
context.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
context.drawImage(images[i] , 0, 0);
i++;
if (i === images.length) i = 0;
}, INTERVAL);
};
const loadImage = (image) => {
return new Promise((resolve) => {
const img = new Image();
img.src = 'https://placehold.it/' + (image * 20) + 'x' + (image * 20);
img.onload = function () {
images.push(img);
resolve();
};
});
};
for(let i = 1; i < 14; i++) {
promises.push(loadImage(i));
}
Promise
.all(promises)
.then(() => {
canvasDraw();
});
})();
&#13;
<canvas id="canvas" width="300" height="300"></canvas>
&#13;