fabric js 在 angular 11 for HTML 5 canvas 中不工作

fabric js not working in angular 11 for HTML 5 canvas

我正在尝试在 canvas 上添加文本框,我正在使用 angular 11 和结构库。 我安装的 NPM npm 我面料 npm 我@types/fabric

HTML

<canvas id="myCanvas" width="1000" height="700" style="border:1px solid #000000;">
</canvas>

应用组件

import { Component } from '@angular/core';
import { fabric } from 'fabric'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'TestProject';

  canvas : any;
  constructor(){
  this.canvas = new fabric.Canvas('myCanvas');
  this.canvas.add(new fabric.Textbox('Hello Fabric!'));
 }
}

当我 运行 这个代码只有 canvas 是可见的。

您正试图在组件的构建期间实例化 canvas。那时实际的 Canvas 元素在 DOM 上还不可用。您需要 运行 组件 ngAfterViewInit 生命周期挂钩中的结构实例化,以确保 Canvas 已准备就绪。像这样:

import { Component, AfterViewInit } from '@angular/core';
import { fabric } from 'fabric'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
title = 'TestProject';
  canvas : any;
  ngAfterViewInit() {
    this.canvas = new fabric.Canvas('myCanvas');
    this.canvas.add(new fabric.Textbox('Hello Fabric!'));
  }
}