简体   繁体   中英

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

I have an array with a bunch of images:

const imgSrcs = ["dashavatar1.jpg", "dashavatar2.jpg", "dashavatar 3.jpg"];

And I'm creating image object from that using the Image constructor:

const images = [];

for (i = 0; i < imgSrcs .length; i++) {
  const image = new Image();
  images.push(image);
}

Now I want to assign the image source and add these image objects on the canvas using fabric.js .

You need to load those images first using const img = new Image() , wait until they are loaded using image.onload and then use ctx.drawImage(img, x, y, width, height) to render it into the 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>

With frabric.js you would do the same thing but using their own fabric.Image.fromUR function:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM