Using Fabric.js – for Interactive HTML5 Canvas Applications



Using Fabric.js – for Interactive HTML5 Canvas Applications

0 2


fabricjs-canvas-slides

Slidedeck for presentation: Using Fabric.js for Interactive HTML5 Canvas Applications

On Github kellypacker / fabricjs-canvas-slides

Using Fabric.js

for Interactive HTML5 Canvas Applications

Kelly Packer / @kellypacker

Hello

Front-End Web Developer at

Oh hey, these are some notes. They'll be hidden in your presentation, but you can see them if you open the speaker notes window (hit 's' on your keyboard).

For the past 2 years

Building an educational application for Pearson ERPI in Canada.

Overview

  • Demo
  • What is Canvas
  • What is Fabric.js
  • Advantages of Fabric.js

Demo

http://erpi.dev/alphabetik/

Native Canvas

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.

Canvas is a rectangle on the page where you can use Javascript to draw stuff.

Canvas Experiment

http://andrew-hoyer.com/experiments/cloth/

Canvas Charts: chartjs.org

http://www.chartjs.org/

Canvas Graphics Example

http://hakim.se/experiments/html5/404/netmag.html

Bitmap vs. Vector

Canvas API

Sample attributes & methods

  • strokeStyle
  • fillStyle
  • fillRect(x, y, width, height)
  • strokeRect(x, y, width, height)
  • clearRect(x, y, width, height)
  • beginPath()
  • closePath()
  • lineTo(x,y)
  • moveTo(x,y)
  • save()
  • restore()

Just the canvas

HTML

<canvas id="myCanvas" width="300" height="200" style="border:1px solid black; background-color: orange;"></canvas>

Simplest canvas example

HTML

<canvas id="myCanvas" width="300" height="200" style="border:1px solid black; background-color: orange;"></canvas>

JS

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d");
// (x, y, width, height)
ctx.fillRect(20, 30, 150, 75);

Native Canvas

Simple Rectangle

JS Bin

Native Canvas

Save state, rotate, restore

JS Bin

Native Canvas

Clear rectangle

JS Bin

Native Canvas

Circle

JS Bin

Native Canvas

Line

JS Bin

Native Canvas

Text

JS Bin

Native Canvas

Image

JS Bin

Fabric.js

Fabric.js is a powerful and simple Javascript HTML5 canvas library.

Fabric provides interactive object model on top of canvas element.

Simplest fabric.js example

Add fabric script in HTML

<script src="js/fabric.min.js"></script>

HTML

<canvas id="myCanvas" width="300" height="200" style="border:1px solid black;"></canvas>

JS

var canvas = new fabric.Element("myCanvas");
var rect = new fabric.Rect({
  top: 100,
  left: 10,
  fill: "red",
  width: 180,
  height: 100
});
canvas.add(rect);

Fabric.js

Simple Rectangle

JS Bin

Fabric creates 2 canvases

Initial HTML

<canvas id="myCanvas" width="300" height="200"></canvas>

Becomes 2 absolutely-positioned, overlaying canvases

<div class="canvas-container">
  <!-- Group selection -->
  <canvas id="myCanvas" width="250" height="300" class="lower-canvas"></canvas>
  <!-- Rendering -->
  <canvas class="upper-canvas" width="250" height="300"></canvas>
</div>

This keeps group selection fast no matter how many objects are currently rendered on canvas.

Fabric.js

Simple Rectangle - Rotated

JS Bin

Fabric.js

Simple Rectangle - Removed

JS Bin

Fabric.js

Shapes

JS Bin

Fabric.js

Custom Shapes, Lines

JS Bin

Fabric.js

SVG Parsing

JS Bin

Fabric.js

Text

JS Bin

Fabric.js

Image

JS Bin

Canvas Profiler

Prototypal Inheritence

fabric.object

  • fabric.Line
  • fabric.Circle
  • fabric.Rect
  • fabric.Group
  • fabric.Text
  • fabric.Ellipse
  • fabric.Image
  • fabric.Polyline
  • fabric.Polygon
  • fabric.Path

Properties

  • angle
  • fill
  • hasControls
  • lockRotation
  • opactiy

Methods

  • .bringToFront()
  • .clone()
  • .getBoundingRect()
  • .getStroke()
  • .moveTo()

Getters

rect.getWidth();

rect.getLeft();
rect.getTop();

rect.getFill(); // rgb(0,0,0)
rect.getStroke();

rect.getOpacity(); // 1

Setters

var rect = new fabric.Rect();
rect.set({ width: 10, height: 20, fill: '#f55', opacity: 0.7 });

Animation

JS Bin

Groups

var text = new fabric.Text('hello world', {
  fontSize: 30
});
var circle = new fabric.Circle({
  radius: 100,
  fill: '#eef',
  scaleY: 0.5
});
var group = new fabric.Group([ text, circle ], {
  left: 150,
  top: 100,
  angle: -10
});
canvas.add(group);

Events

canvas.on('object:moving', function(e) {
  var activeObj = e.target;
  console.log(activeObj.get('left'), activeObj.get('top'));
});

// attach an event to an object
rect.on("mousedown", closeTool);

Subclassing

var LabeledRect = fabric.util.createClass(fabric.Rect, {

  type: 'labeledRect',

  initialize: function(options) {
    options || (options = { });

    this.callSuper('initialize', options);
    this.set('label', options.label || '');
  },

  toObject: function() {
    return fabric.util.object.extend(this.callSuper('toObject'), {
      label: this.get('label')
    });
  },

  _render: function(ctx) {
    this.callSuper('_render', ctx);

    ctx.font = '20px Helvetica';
    ctx.fillStyle = '#333';
    ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
  }
});

Other awesomeness

Fast

Benchmarks150 random objects: Initialization: 151ms Rendering: 79ms Total time: 230ms

canvas.renderOnAddRemove = false

Test-Driven

2400+ tests

Unit, functional, import/export

Browser Support

  • Firefox 2+
  • Safari 3+
  • Opera 9.64+
  • Chrome (all versions should work)
  • IE9, IE10, IE11

If you are brave, there is some IE<9 support with excanvas

In development

  • Currently in development, new features all the time
  • Great docs
  • responsive community (Google Group)

Save/Restore 3.0

Canvas can be serialized to JSON or SVG and restored

Modular

(60 small classes, modules, mixins)

node build.js modules=text,serialization,parser

https://www.youtube.com/watch?v=lMtjczxTSjU

Thanks

Kelly Packer / @kellypacker

References