Introduction to FabricJS


By Kamil Gałuszka S4F Team

FabricJS is awesome :-)


Example in plain JavaScript

var canvasEl = document.getElementById('myCanvas');

// get 2d context to draw on (the "bitmap" mentioned earlier)
var ctx = canvasEl.getContext('2d');

// set fill color of context
ctx.fillStyle = 'red';

// create rectangle at a 100,100 point, with 20x20 dimensions
ctx.fillRect(100, 100, 20, 20);

ctx.translate(100, 100);

ctx.rotate(Math.PI / 180 * 45);

ctx.fillRect(-10, -10, 20, 20);

FabricJS is awesome


var canvas = new fabric.Canvas('myCanvas');

// create a rectangle object
var rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20,
  angle: 45
});

canvas.add(rect);

FabricJS obj.set()



  • Set can take object
  • Any arguments key, value



rect.set('fill', 'red');
rect.set({ strokeWidth: 5, stroke: 'rgba(100,200,200,0.5)' });
rect.set('angle', 15).set('flipY', true);
    

FabricJS refreshing Canvas



   
canvas.add(rect)
...
rect.set({ left: 20, top: 50 });
canvas.renderAll();
    
    

FabricJS basic shapes


  1. fabric.Circle
  2. fabric.Ellipse 
  3. fabric.Line 
  4. fabric.Polygon 
  5. fabric.Polyline 
  6. fabric.Rect 
  7. fabric.Triangle

Animation framework


.animate

  • onChange: canvas.renderAll.bind(canvas),
  • duration: 1000,
  • easing: fabric.util.ease.easeOutBounce

DEMO Time :)

Thanks