1

I'm using FabricJS v1.5.0 and have a problem when manipulated pixel by pixel on the canvas.

this.canvas = new this.fabric.Canvas('canvas');
let imageData = this.canvas.contextContainer.getImageData(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
//here a changed imageData

this.canvas.contextContainer.putImageData(imageData, 0, 0);
//data seted in canvas.

let imageAdd = new this.fabric.Image(image, {
          left: 100,
          top: 100,
          width: 100,
          height: 100
        });
this.canvas.add(imageAdd).setActiveObject(imageAdd);
//in this moment, the canvas don't have more the imageData setted

Why add image clear imageData? I need to transform imageData in FabricJS Object to add in canvas?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

2 Answers2

2

Yes, I think you do need to turn your image data into a fabricjs image. When you need to save the state of the canvas you can do this:

var dataUrl;
....
// Save canvas state
dataUrl = canvas.toDataURL()

// Make changes to the canvas

Then when you need to restore the canvas from it's saved state:

var img = fabric.Image.fromURL(dataUrl, function (i) {
    canvas.clear();
    canvas.add(i);
    canvas.renderAll();
});

You should then be able to add other images as before.

John M
  • 2,510
  • 6
  • 23
  • 31
1

What you need to find out is if your image is actually an image object, because fabric.Image() needs your image object.

If it's a URL or Blob format of your image ( which I guess it is ), you need to use fabric.Image.fromURL() and provide the src of the image not the whole image object.

Here is an example on how to create an instance of fabric.Image from a URL string

fabric.Image.fromURL(link, function(img) {
    img.set({
        id : 'someId',
        width : canvas.width / 2,
        height : canvas.height / 2
    });
    canvas.add(img).renderAll().setActiveObject(img);
});
jdrake
  • 333
  • 4
  • 17