How to use / include fabricjs in Angular2

时光总嘲笑我的痴心妄想 提交于 2019-11-30 00:54:08

I can use fabric.js without the line

import { fabric } from 'fabric';

loading the script on index.html and declaring the library on the ts file:

import { Component } from '@angular/core';
declare var fabric: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  printValue() {
    console.log(fabric.version);
  };
}

Out on browser console:

1.6.7  app.component.ts:13

Modern usage:

  1. Install Fabric: npm i fabric
  2. Install types: npm i @types/fabric

Demo with Angular 5.2.8 and Fabric 2.2.2

HTML

<div>
  <canvas id="myCanvas" width="500" height="500"></canvas>
</div>

TypeScript

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
  canvas: any;

  ngOnInit() {
    this.canvas = new fabric.Canvas('myCanvas');
    this.canvas.add(new fabric.IText('Hello Fabric!'));
  }
}

In this way I added Fabric.js to my Angular project created using angular-cli:

1) Install Cairo on your system.

Note: Cairo is a system library which powers node-canvas, which Fabric.js relies on. When the installation is complete, you may need to restart your terminal or command prompt before installing fabric.

2) Install Fabric.js

npm install fabric --save 

3) Install TypeScript definitions for Fabric.js

typings install fabric --source dt --save

4) Import fabric in required ts file

import 'fabric';
declare const fabric: any;

Here you can find my "Hello World" Angular + Fabric.js project.

Other links:

Fabricjs website

Fabricjs docs

Fabric and type definitions

I have similar issue recently, the following steps resolved it. (angular 2.3.1 + angular-cli 1.0.0-beta.31)

  1. Create a file called typings.d.ts under your src folder.
  2. Put a line of code declare module 'fabric'; in it.
  3. Then you can import { fabric } from 'fabric'; in your Angular 2 components.

I also have same problem, following is my solution.

  1. Install fabric

    $ npm install fabric --save

  2. Generate typings module

    $ typings install fabric --source dt --save

  3. Put declare module 'fabric'; at the end of src/typings.d.ts

  4. Then import import { fabric } from 'fabric'; in the Angular2 Component.

It is working fine and giving fabric autocomplete suggestions also.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!