我有一个带有一堆图像的数组:
const imgSrcs = ["dashavatar1.jpg", "dashavatar2.jpg", "dashavatar 3.jpg"];
并且我正在使用Image
构造函数从该对象创建图像对象:
const images = [];
for (i = 0; i < imgSrcs .length; i++) {
const image = new Image();
images.push(image);
}
现在我要分配图像源,并使用fabric.js
在画布上添加这些图像对象。
您需要先使用const img = new Image()
加载这些图像,等待直到使用const img = new Image()
加载它们,然后使用image.onload
将其渲染到画布中:
使用const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const innerWidth = canvas.width = window.innerWidth;
const innerHeight = canvas.height = window.innerHeight;
const images = [
'https://i.stack.imgur.com/L5XWd.png',
'https://i.stack.imgur.com/SnOAO.png',
];
images.forEach((src, i) => {
const image = new Image();
image.src = src;
image.onload = () => {
ctx.drawImage(image, innerWidth / 2 - 16, 8 + 40 * i, 32, 32);
};
});
,您将执行相同的操作,但使用自己的body {
margin: 0;
height: 100vh;
}
#canvas {
width: 100%;
height: 100%;
}
函数: