我有一个带有一堆图像的数组:
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()
,等到使用加载它们image.onload
,然后再使用ctx.drawImage(img, x, y, width, height)
将其渲染到画布中:
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%;
}
<canvas id="canvas"></canvas>
与frabric.js
您将执行相同的操作,但使用其自己的fabric.Image.fromUR
功能:
const canvas = new fabric.Canvas('canvas');
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',
];
canvas.setWidth(innerWidth);
canvas.setHeight(innerHeight);
images.forEach((src, i) => {
fabric.Image.fromURL(src, (image) => {
const oImage = image.set({
left: canvas.getWidth() / 2 - 16,
top: 8 + 40 * i,
scaleX: 32 / image.width,
scaleY: 32 / image.height,
scale: 1,
});
canvas.add(oImage);
});
});
body {
margin: 0;
height: 100vh;
}
#canvas {
width: 100%;
height: 100%;
}
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.3/fabric.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句