如何使用 fabric.js 将 URL 中的图像添加到 HTML canvas 中并调整其大小?

How can I add and resize images from URLs into an HTML canvas using fabric.js?

我有一个包含一堆图像的数组:

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 在 canvas 上添加这些图像对象。

您需要先使用 const img = new Image(), wait until they are loaded using image.onload and then use ctx.drawImage(img, x, y, width, height) 加载这些图像以将其渲染到 canvas:

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>