Search code examples
angularcanvasfabricjs

How to load canvas data to a string only if user draws something on it using angular?


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);
}
}

Solution

  • 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.