How to Create and Edit Canvas Using angular and fabric js

First Create New angular project

ng new canvas-edit

Install Fabric js using below command

npm install fabric –save

In your component.ts file import fabric js

import { fabric } from ‘fabric’;

Declare the variables as below

private canvas: any;
 private textString: string;
 private size: any = {
   width: 1200,
   height: 1000
 };
 private OutputContent: string;

Then Initialize the values and objects in ngOnInit() function

this.canvas = new fabric.Canvas('canvas', {
  hoverCursor: 'pointer',
  selection: true,
  selectionBorderColor: 'blue'
});
this.textString = null;
this.canvas.setWidth(this.size.width);
this.canvas.setHeight(this.size.height);
this.OutputContent = null;

Add some text to Canvas using below function

addText() {
    let textString = this.textString;
    let text = new fabric.IText(textString, {
      left: 10,
      top: 10,
      fontFamily: 'helvetica',
      angle: 0,
      fill: '#000000',
      scaleX: 0.5,
      scaleY: 0.5,
      fontWeight: '',
      hasRotatingPoint: true
    });
    this.extend(text, this.randomId());
    this.canvas.add(text);
    this.selectItemAfterAdded(text);
    this.textString = '';
}

extend(obj, id) {
	obj.toObject = (function (toObject) {
	  return function () {
		return fabric.util.object.extend(toObject.call(this), {
		  id: id
		});
	  };
	})(obj.toObject);
}
//======= this is used to generate random id of every object ===========
randomId() {
	return Math.floor(Math.random() * 999999) + 1;
}
//== this function is used to active the object after creation ==========
selectItemAfterAdded(obj) {
	this.canvas.discardActiveObject().renderAll();
	this.canvas.setActiveObject(obj);
}

Then Create Shapes like Triangle, square, circle using below code

addFigure(figure) {
	let add: any;
	switch (figure) {
	  case 'rectangle':
		add = new fabric.Rect({
		  width: 200, height: 100, left: 10, top: 10, angle: 0,
		  fill: '#3f51b5'
		});
		break;
	  case 'square':
		add = new fabric.Rect({
		  width: 100, height: 100, left: 10, top: 10, angle: 0,
		  fill: '#4caf50'
		});
		break;
	  case 'triangle':
		add = new fabric.Triangle({
		  width: 100, height: 100, left: 10, top: 10, fill: '#2196f3'
		});
		break;
	  case 'circle':
		add = new fabric.Circle({
		  radius: 50, left: 10, top: 10, fill: '#ff5722'
		});
		break;
	}
	this.extend(add, this.randomId());
	this.canvas.add(add);
	this.selectItemAfterAdded(add);
}

Export your designed canvas to various formats(JSON, SVG)

  ExportToContent(input) {
    if(input == 'json'){
      this.OutputContent = JSON.stringify(this.canvas);
    }else if(input == 'svg'){
     this.OutputContent = this.canvas.toSVG();
    }
  }

Final HTML Code like Below.

<input type="text" [(ngModel)]="textString"/><button (click)="addText()">Add</button>
   
<button (click)="addFigure('triangle')">Triangle</button>
<button (click)="addFigure('circle')">Circle</button>
<button (click)="addFigure('square')">Square</button>
<button (click)="addFigure('rectangle')">Rectangle</button>

  

<button (click)="ExportToContent('json')">Generate Json</button>
<button (click)="ExportToContent('svg')">Generate SVG</button>
<br/>
<code>{{OutputContent}}</code>
<canvas id="canvas"></canvas>

<router-outlet></router-outlet>

Git Link: https://github.com/iamchandu/how-to-create-and-edit-canvas-using-angular-and-fabric-js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with WordPress.com
Get started
%d bloggers like this: