gpt4 book ai didi

javascript - Canvas 不绘制图像

转载 作者:行者123 更新时间:2023-12-02 14:25:39 24 4
gpt4 key购买 nike

我的 Canvas 有问题,我正在尝试绘制图像,但无法正常工作,正如您所看到的那样,我正在将图像加载到数组中,并等待所有加载完毕后,我每次迭代都会更改图像,但没有画任何一个,请看我的代码。我找不到错误:(

(() => {
"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

<canvas id="canvas"></canvas>

最佳答案

您需要为 Canvas 指定宽度和高度。

使用占位符图像:

(() => {
"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();
});
})();
<canvas id="canvas" width="300" height="300"></canvas>

根据您正在执行的操作,您可能需要在渲染之间清除 Canvas 。

(() => {
"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();
});
})();
<canvas id="canvas" width="300" height="300"></canvas>

关于javascript - Canvas 不绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com