Home > Enterprise >  Load array of images in Canvas
Load array of images in Canvas

Time:03-28

I want to load an array of images to canvas but don't know how to achieve it. I would appreciate it if I could get some pointers on how I can achieve it. I am using class-based component on React.

My Code:

drawCanvas(img, prevProps) {

const node = this.canvasRef.current;
const context = node.getContext("2d");


context.drawImage(img, 0, 0);
}

// imgArray = [image1, image2, image3]

componentDidUpdate(prevProps) {

  const imageArray = Array.from(imgArray).map((image) => image)

  console.log(imageArray)
  
  var img = new Image();
  img.src = this.props.image;
  img.onload = () => this.drawCanvas(img, prevProps);
}

CodePudding user response:

None of this really involves React at all, other than you need to get a hold of the canvas reference, which you're doing.

If you already have the array of image objects, it's actually pretty straightforward. Just call drawImage() for each image in the array. You'll probably want to clear before you start drawing them, so the last ones don't bleed through and create weirdness.

context.clearRect(0, 0, canvas.width, canvas.height);
imageArray.forEach(image => {
  context.drawImage(image, 0, 0);
});

And that's it. Pretty straightforward.

  • Related