Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

Fabric.js: An Interactive Object Model and SVG Parser for the Canvas Element

August 27th 2010

Kangax has released Fabric.js, a library that aims to make interacting with objects drawn on the canvas element easier.

Fabric.js started as a foundation for design editor on printio.ru — interactive online store with ability to create your own designs. The idea was to create Javascript-based editor, which would make it easy to manipulate vector shapes and images on T-Shirts. Since performance was one of the most critical requirements, we chose canvas over SVG. While SVG is excellent with static shapes, it’s not as performant as canvas when it comes to dynamic manipulation of objects (movement, scaling, rotation, etc.). Fabric.js was heavily inspired by Ernest Delgado’s canvas experiment. In fact, code from Ernest’s experiment was the foundation of an entire framework. Later, Fabric.js grew into a collection of distinct object types and got an SVG-to-canvas parser.

Using Fabric.js, you can create and populate objects on canvas; objects like simple geometrical shapes — rectangles, circles, ellipses, polygons, or more complex shapes consisting of hundreds or thousands of simple paths. You can then scale, move, and rotate these objects with the mouse; modify their properties — color, transparency, z-index, etc. You can also manipulate these objects altogether — grouping them with a simple mouse selection.

image

As you can see in the demo, Fabric.js is fast and produces a great user experience for manipulating a design - right in the browser.  It is also simple to use from your own code:

var canvas = new fabric.Element('canvas');

var rect = new fabric.Rect({
  top: 100,
  left: 100,
  width: 60,
  height: 70,
  fill: 'red'
});

canvas.add(rect);

Because Fabric.js has a SVG parser, you can import complex shapes from a vector editor like Adobe Illustrator or Inkscape into your canvas element very easily.

You can check out the demo here, and get the code on Github.  Great work!