Sleepz
Sleepz

Reputation: 87

How to add multiple image to canvas using fabricjs

I have read several questions/answers about this topic, but I can't seem to find my solution. So sorry if you guys find this question duplicated.

Here is my situation; Let's say I have a menu for user to click on it and it will display the image of that selected item on canvas, also user can resize/drag/drop that image as they want. Right now I can make it works only one time with this code

addAction(selectedAction: any) {
  var canvas = new fabric.Canvas('c');
  var imgObj = new Image();
  imgObj.src = selectedAction.image;
  imgObj.onload = function() {
    var imgInstance = new fabric.Image(imgObj, {
        left: 200,
        top: 200,
      });
    canvas.add(imgInstance);
  }

The problem is when user click another item in the menu, the previous item that was on the canvas disappear, instead the current item display on the canvas. But if I click on that image, it will disappear and the previous image display on the canvas.

I want them BOTH stay on the canvas at the same time. Please advice.

Upvotes: 3

Views: 3248

Answers (1)

Ben
Ben

Reputation: 979

Real quick answer: http://jsfiddle.net/8yf15nqp/1/.

var canvas = ...// setup canvas

function addImage (url) {
    fabric.Image.fromURL(url, function (img) {
        // deal with image
       canvas.add(img);
    });
}

Setup a function to handle adding and then call it when you want to add a new image. I'd assume you'll want to pass the url to the function and do other stuff, but this is a pretty stripped down example.

Upvotes: 5

Related Questions