Search code examples
angularfabricjs

How to implement Fabricjs Align guidelines in Angular?


We are trying to implement the FabricJs Guidelines-(Aligning, Snapping) as per the link: https://github.com/fabricjs/fabric.js/blob/master/lib/aligning_guidelines.js

These are steps, we followed (as per link : How to call JavaScript functions from Typescript in Angular 5?):

Step 1: Copied these js's into the assets/folder as guidelines.services.js

Step 2: Declared those functions on .ts files

ISSUE: Still facing issues - delay in loading shapes in implementing it.

Kindly help us with relevant Demo/ implementation /Documents.


Solution

  • The mentioned above steps are right, except they need to be initialized at ngAfterContentInit(). Codes will be like this.

    //#region Methods which are defined in the .js files.
    
    declare function initCenteringGuidelines(canvas: fabric.Canvas):void;
    declare function initAligningGuidelines(canvas: fabric.Canvas):void;
    declare function initKeyBoardMovement (canvas: fabric.Canvas,e:any):void;
    
    //#endregion
    
    @Component({
      selector: 'app-fabric-canvas',
      templateUrl: './fabric-canvas.component.html',
      styleUrls: ['./fabric-canvas.component.scss'],
    })
    
    
    ngAfterContentInit() {
        this.ngZone.runOutsideAngular(() => {
          if (this.eventHandler.canvas) {
            this.eventHandler.canvas.dispose();
          }
          this.canvas = new fabric.Canvas('canvas', {
            selection: true,
            preserveObjectStacking: true,
            backgroundColor:'#2d2d2d', //need to add to Theme,
            fireRightClick: true,  // <-- enable firing of right click events
            fireMiddleClick: true, // <-- enable firing of middle click events
            stopContextMenu: true, // <--  prevent context menu from showing
          });
    
        
          initCenteringGuidelines(this.canvas);
          initAligningGuidelines(this.canvas);   
        });
      }