I am trying to add textbox on canvas, I am using angular 11 and fabric library. NPM that I have installed npm i fabric npm i @types/fabric
HTML
<canvas id="myCanvas" width="1000" height="700" style="border:1px solid #000000;">
</canvas>
app componnet
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!'));
}
}
When I run this code only canvas is visible nothing else.
You are trying to instantiate the canvas during construction time of your component. At that time the actual Canvas Element, is not available on the DOM yet. You need to run the fabric instantiation inside the ngAfterViewInit
lifecycle hook of your component, to make sure the Canvas is ready. Something like this:
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!'));
}
}