0

I'm trying to store canvas data to a variable in Angular only if the user draws or makes any changes to it.

I'm not getting how to do this automatically.

My component.html file looks something like this:

<canvas id="canvas"></canvas>

My component.ts file looks something like this:

import { fabric } from 'fabric';

@Component({
  selector: "app-drawspace",
  templateUrl: "./drawspace.component.html",
  styleUrls: ["./drawspace.component.css"]
})
export class DrawspaceComponent implements OnInit {
canvasData: any;
constructor(){}
canvas: any;
ngOnInit() {
  this.canvas = new fabric.Canvas('canvas', { 
    width: 1000,
    height: 500,
    selection: false,
    isDrawingMode: true
  });
 }
 // I want this loadjson() to to be called automatically whenever a user draws something on the canvas
 loadjson() {
  this.canvasData = JSON.stringify(this.canvas);
  console.log(this.canvasData);
}
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Avatar
  • 13
  • 3

1 Answers1

0

You could leverage the path:created event of the fabric js library.

Try the following

export class AppComponent implements OnInit {
  canvasData: any;
  constructor() {}
  canvas: any;

  ngOnInit() {
    this.canvas = new fabric.Canvas('canvas', {
      width: 1000,
      height: 500,
      selection: false,
      isDrawingMode: true
    });

    // Reason for `bind(this)`: https://stackoverflow.com/q/20279484/6513921
    this.canvas.on('path:created', this.loadjson.bind(this));
  }

  loadjson() {
    this.canvasData = JSON.stringify(this.canvas);
    console.log(this.canvasData);
  }
}

Working example: Stackblitz

There's a plethora of other fabric js events that you could look into.

ruth
  • 29,535
  • 4
  • 30
  • 57
  • Hey, Its not calling loadjson when a image is added into the canvas. I don't know why. – Avatar Aug 11 '21 at 12:21
  • @Avatar: I'm not sure how you're adding the image to the canvas, but as the name implies `path:created` event is triggered when a user draws something on the canvas. And as mentioned in the answer, if you look at other events, the one you're looking for might be `object:added`. Try: `this.canvas.on('object:created', this.loadjson.bind(this));`. If this too doesn't work, try to use other events mentioned in the docs. – ruth Aug 11 '21 at 12:39
  • I tried `this.canvas.on('object:created', this.loadjson.bind(this))` but this doesn't work, so looked into docs and tried `this.canvas.on('object:added', this.loadjson.bind(this))` , this is creating a infinite loop. And I'm adding image using button which in turn triggers a function and it uploads the image to firebase storage and returns a imageurl, and by `fabric.Image.fromURL(this.imgURL, function(img) { canvas.add(img);})` I'm adding the image. – Avatar Aug 11 '21 at 12:49