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
A simple and powerful Javascript HTML5 canvas library.
Features
- Out of the box interactions such as scale, move, rotate, skew, group...
- Built in shapes, controls, animations, image filters, gradients, patterns, brushes...
JPG
, PNG
, JSON
and SVG
i/o- Typed and modular
- Unit tested
Supported Browsers/Environments
Context | Supported Version | Notes |
---|
Firefox | โ๏ธ | modern version (tbd) |
Safari | โ๏ธ | version >= 10.1 |
Opera | โ๏ธ | chromium based |
Chrome | โ๏ธ | modern version (tbd) |
Edge | โ๏ธ | chromium based |
Edge Legacy | โ | |
IE11 | โ | |
Node.js | โ๏ธ | Node.js installation |
Fabric.js Does not use transpilation by default, the browser version we support is determined by the level of canvas api we want to use and some js syntax. While JS can be easily transpiled, canvas API can't.
Installation
$ npm install fabric --save
// or
$ yarn add fabric
import { fabric } from 'fabric';
const fabric = require('fabric').fabric;
Browser
See browser modules for using es6 imports in the browser or use a dedicated bundler.
Node.js
Fabric.js depends on node-canvas for a canvas implementation (HTMLCanvasElement
replacement) and jsdom for a window
implementation on node.
This means that you may encounter node-canvas
limitations and bugs.
Follow these instructions to get node-canvas
up and running.
Quick Start
Plain HTML
<canvas id="canvas" width="300" height="300"></canvas>
<script src="https://cdn.jsdelivr.net/npm/fabric"></script>
<script>
const canvas = new fabric.Canvas('canvas');
const rect = new fabric.Rect({
top: 100,
left: 100,
width: 60,
height: 70,
fill: 'red',
});
canvas.add(rect);
</script>
ReactJS
import React, { useEffect, useRef } from 'react';
import { fabric } from 'fabric';
export const FabricJSCanvas = () => {
const canvasEl = useRef(null);
useEffect(() => {
const options = { ... };
const canvas = new fabric.Canvas(canvasEl.current, options);
updateCanvasContext(canvas);
return () => {
updateCanvasContext(null);
canvas.dispose();
}
}, []);
return (<canvas width="300" height="300" ref={canvasEl}/>)
});
Node.js
const http = require('http');
const { fabric } = require('fabric');
const port = 8080;
http
.createServer((req, res) => {
const canvas = new fabric.Canvas(null, { width: 100, height: 100 });
const rect = new fabric.Rect({ width: 20, height: 50, fill: '#ff0000' });
const text = new fabric.Text('fabric.js', { fill: 'blue', fontSize: 24 });
canvas.add(rect, text);
canvas.renderAll();
if (req.url === '/download') {
res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Disposition', 'attachment; filename="fabric.png"');
canvas.createPNGStream().pipe(res);
} else if (req.url === '/view') {
canvas.createPNGStream().pipe(res);
} else {
const imageData = canvas.toDataURL();
res.writeHead(200, '', { 'Content-Type': 'text/html' });
res.write(`<img src="${imageData}" />`);
res.end();
}
})
.listen(port, (err) => {
if (err) throw err;
console.log(
`> Ready on http://localhost:${port}, http://localhost:${port}/view, http://localhost:${port}/download`
);
});
Other Solutions
More Resources
Credits