仅当用户使用 angular 在字符串上绘制内容时,如何将 canvas 数据加载到字符串?

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

我正在尝试将 canvas 数据存储到 Angular 中的变量,仅当用户对其进行绘制或对其进行任何更改时。

我不知道如何自动执行此操作。

我的 component.html 文件看起来像这样:

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

我的 component.ts 文件看起来像这样:

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

您可以利用 fabric js 库的 path:created 事件。

尝试以下方法

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)`: 
    this.canvas.on('path:created', this.loadjson.bind(this));
  }

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

工作示例:Stackblitz

您可以查看大量其他 fabric js events