What is fabric?
The 'fabric' npm package is a powerful and versatile library for working with HTML5 canvas. It provides an object model on top of the canvas element, making it easier to create, manipulate, and interact with graphics. Fabric.js is particularly useful for creating rich, interactive applications such as image editors, drawing applications, and data visualization tools.
What are fabric's main functionalities?
Creating and Manipulating Shapes
This feature allows you to create and manipulate basic shapes like rectangles, circles, and polygons. The code sample demonstrates how to create a red rectangle and add it to the canvas.
const fabric = require('fabric').fabric;
const canvas = new fabric.Canvas('c');
const rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Working with Images
Fabric.js makes it easy to work with images. You can load images from URLs, manipulate them, and add them to the canvas. The code sample shows how to load an image from a URL and add it to the canvas.
const fabric = require('fabric').fabric;
const canvas = new fabric.Canvas('c');
fabric.Image.fromURL('http://example.com/image.jpg', function(img) {
img.set({ left: 100, top: 100 });
canvas.add(img);
});
Text Manipulation
Fabric.js provides robust text manipulation capabilities. You can create text objects, style them, and add them to the canvas. The code sample demonstrates how to create a text object with the content 'Hello, world!' and add it to the canvas.
const fabric = require('fabric').fabric;
const canvas = new fabric.Canvas('c');
const text = new fabric.Text('Hello, world!', {
left: 100,
top: 100,
fill: 'blue'
});
canvas.add(text);
Event Handling
Fabric.js supports event handling for interactive applications. You can attach event listeners to objects on the canvas. The code sample shows how to attach a 'selected' event listener to a rectangle.
const fabric = require('fabric').fabric;
const canvas = new fabric.Canvas('c');
const rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
rect.on('selected', function() {
console.log('Rectangle selected');
});
Other packages similar to fabric
konva
Konva is a 2D canvas library for creating desktop and mobile applications. It provides a high-level API for working with shapes, images, and text, similar to Fabric.js. However, Konva is optimized for performance and is often used in applications requiring high frame rates, such as games and animations.
paper
Paper.js is an open-source vector graphics scripting framework that runs on top of the HTML5 Canvas. It offers a clean Scene Graph/Document Object Model (DOM) and a lot of powerful functionality to create and work with vector graphics. Compared to Fabric.js, Paper.js is more focused on vector graphics and offers more advanced path manipulation capabilities.
p5
p5.js is a JavaScript library that makes coding accessible for artists, designers, educators, and beginners. It is built on top of the HTML5 Canvas and provides a simple way to create graphics and interactive content. While p5.js is more general-purpose and beginner-friendly, Fabric.js offers more specialized tools for working with canvas-based applications.
Fabric.js
Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. It is also 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.
Non-Technical Introduction to Fabric
Fabric.js allows you to easily create simple shapes like rectangles, circles, triangles and other polygons or more complex shapes made up of many paths, onto the HTML <canvas>
element on a webpage using JavaScript. Fabric.js will then allow you to manipulate the size, position and rotation of these objects with a mouse. It’s also possible to change some of the attributes of these objects such as their color, transparency, depth position on the webpage or selecting groups of these objects using the Fabric.js library. Fabric.js will also allow you to convert an SVG image into JavaScript data that can be used for putting it onto the <canvas>
element.
Contributions are very much welcome!
Goals
Supported browsers
- Firefox 4+
- Safari 5+
- Opera 9.64+
- Chrome (all versions)
- Edge (chromium based, all versions)
- IE11 and Edge legacy, supported but deprecated.
You can run automated unit tests right in the browser.
History
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.
Installation Instructions
Install with bower
$ bower install fabric
Install with npm
Note: If you are using Fabric.js in a Node.js script, you will depend from node-canvas.node-canvas
is an html canvas replacement that works on top of native libraries.
Please follow the instructions located here in order to get it up and running.
$ npm install fabric --save
After this, you can import fabric like so:
const fabric = require("fabric").fabric;
Or you can use this instead if your build pipeline supports ES6 imports:
import { fabric } from "fabric";
NOTE: es6 imports won't work in browser or with bundlers which expect es6 module like vite. Use commonjs syntax instead.
See the example section for usage examples.
Building
-
Install Node.js
-
Build distribution file [~77K minified, ~20K gzipped]
$ node build.js
2.1 Or build a custom distribution file, by passing (comma separated) module names to be included.
$ node build.js modules=text,serialization,parser
// or
$ node build.js modules=text
// or
$ node build.js modules=parser,text
// etc.
By default (when none of the modules are specified) only basic functionality is included.
See the list of modules below for more information on each one of them.
Note that default distribution has support for static canvases only.
To get minimal distribution with interactivity, make sure to include corresponding module:
$ node build.js modules=interaction
2.2 You can also include all modules like so:
$ node build.js modules=ALL
2.3 You can exclude a few modules like so:
$ node build.js modules=ALL exclude=gestures,image_filters
-
Create a minified distribution file
# Using YUICompressor (default option)
$ node build.js modules=... minifier=yui
# or Google Closure Compiler
$ node build.js modules=... minifier=closure
-
Enable AMD support via require.js (requires uglify)
$ node build.js requirejs modules=...
-
Create source map file for better productive debugging (requires uglify or google closure compiler).
More information about source maps.
$ node build.js sourcemap modules=...
If you use google closure compiler you have to add sourceMappingURL
manually at the end of the minified file all.min.js (see issue https://code.google.com/p/closure-compiler/issues/detail?id=941).
//# sourceMappingURL=fabric.min.js.map
-
Ensure code guidelines are met (prerequisite: npm -g install eslint
)
$ npm run lint && npm run lint_tests
Testing
-
Install Node.js
-
Install NPM, if necessary
-
Install NPM packages
$ npm install
-
Run test suite
Make sure testem is installed
$ npm install -g testem
Run tests Chrome and Node (by default):
$ testem
See testem docs for more info: https://github.com/testem/testem
Demos
Who's using Fabric?
Documentation
Documentation is always available at http://fabricjs.com/docs/.
Also see official 4-part intro series, presentation from BK.js and presentation from Falsy Values for an overview of fabric.js, how it works, and its features.
Optional modules
These are the optional modules that could be specified for inclusion, when building custom version of fabric:
- text — Adds support for static text (
fabric.Text
) - itext — Adds support for interactive text (
fabric.IText
, fabric.Textbox
) - serialization — Adds support for
loadFromJSON
, loadFromDatalessJSON
, and clone
methods on fabric.Canvas
- interaction — Adds support for interactive features of fabric — selecting/transforming objects/groups via mouse/touch devices.
- parser — Adds support for
fabric.parseSVGDocument
, fabric.loadSVGFromURL
, and fabric.loadSVGFromString
- image_filters — Adds support for image filters, such as grayscale of white removal.
- easing — Adds support for animation easing functions
- node — Adds support for running fabric under node.js, with help of jsdom and node-canvas libraries.
- freedrawing — Adds support for free drawing
- gestures — Adds support for multitouch gestures with help of Event.js
- object_straightening — Adds support for rotating an object to one of 0, 90, 180, 270, etc. depending on which is angle is closer.
- animation — Adds support for animation (
fabric.util.animate
, fabric.util.requestAnimFrame
, fabric.Object#animate
, fabric.Canvas#fxCenterObjectH/#fxCenterObjectV/#fxRemove
)
Additional flags for build script are:
- requirejs — Makes fabric requirejs AMD-compatible in
dist/fabric.js
. Note: an unminified, requirejs-compatible version is always created in dist/fabric.require.js
- no-strict — Strips "use strict" directives from source
- no-svg-export — Removes svg exporting functionality
- sourcemap - Generates a sourceMap file and adds the
sourceMappingURL
(only if uglifyjs is used) to dist/fabric.min.js
For example:
node build.js modules=ALL exclude=json no-strict no-svg-export
Examples of use
Adding red rectangle to canvas
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="300" height="300"></canvas>
<script src="lib/fabric.js"></script>
<script>
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
top : 100,
left : 100,
width : 60,
height : 70,
fill : 'red'
});
canvas.add(rect);
</script>
</body>
</html>
Helping Fabric
Staying in touch
Follow @fabric.js, @kangax or @AndreaBogazzi on twitter.
Questions, suggestions — fabric.js on Google Groups.
See Fabric questions on Stackoverflow,
Fabric snippets on jsfiddle
or codepen.io.
Fabric on LibKnot.
Get help in Fabric's IRC channel — irc://irc.freenode.net/#fabric.js
Credits
MIT License
Copyright (c) 2008-2015 Printio (Juriy Zaytsev, Maxim Chernyak)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.