Top Related Projects
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Quick Overview
Fabric.js is a powerful and flexible JavaScript library for working with HTML5 canvas. It provides an interactive object model on top of canvas and enables object manipulation, animation, and image filters. Fabric.js simplifies complex canvas operations and makes it easier to create rich, interactive graphics and applications.
Pros
- Easy to use with a high-level API for canvas manipulation
- Supports both object-oriented and stateless modes of operation
- Extensive set of features including SVG parsing, image filters, and animations
- Active community and regular updates
Cons
- Large file size, which may impact page load times
- Learning curve can be steep for advanced features
- Performance may degrade with a large number of objects on canvas
- Limited documentation for some advanced features
Code Examples
Creating a simple canvas with a rectangle:
const canvas = new fabric.Canvas('myCanvas');
const rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Adding interactivity to objects:
const circle = new fabric.Circle({
radius: 30,
fill: 'blue',
left: 50,
top: 50
});
circle.on('mousedown', function() {
console.log('Circle clicked!');
});
canvas.add(circle);
Applying image filters:
fabric.Image.fromURL('path/to/image.jpg', function(img) {
img.filters.push(new fabric.Image.filters.Grayscale());
img.applyFilters();
canvas.add(img);
});
Getting Started
-
Include Fabric.js in your HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.1/fabric.min.js"></script>
-
Create a canvas element in your HTML:
<canvas id="myCanvas" width="600" height="400"></canvas>
-
Initialize Fabric.js canvas in your JavaScript:
const canvas = new fabric.Canvas('myCanvas');
-
Start adding objects to your canvas:
const rect = new fabric.Rect({ left: 100, top: 100, fill: 'green', width: 50, height: 50 }); canvas.add(rect);
You're now ready to explore more features and create interactive canvas applications with Fabric.js!
Competitor Comparisons
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Pros of fabric.js
- Extensive documentation and community support
- Rich set of features for canvas manipulation and interactive graphics
- Regular updates and active maintenance
Cons of fabric.js
- Learning curve for complex implementations
- Performance can be slower for large-scale projects with many objects
Code comparison
Both repositories refer to the same project, so there's no code comparison to be made. Here's a sample of fabric.js usage:
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Summary
fabric.js is a powerful HTML5 canvas library that provides a wide range of features for creating and manipulating interactive graphics. It offers excellent documentation and community support, making it easier for developers to get started and solve problems. The library is regularly updated and actively maintained, ensuring compatibility with modern web technologies.
However, fabric.js can have a steeper learning curve for complex implementations, especially when dealing with advanced features or custom objects. Additionally, performance may be a concern for large-scale projects with numerous objects on the canvas, as rendering and interactions can become slower.
Overall, fabric.js is a versatile and feature-rich library for canvas manipulation, suitable for a wide range of projects from simple graphics to complex interactive applications.
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
Pros of Konva
- Lighter weight and faster performance, especially for complex animations
- Better touch and mobile support out of the box
- More straightforward API for creating and manipulating shapes
Cons of Konva
- Smaller community and ecosystem compared to Fabric.js
- Lacks some advanced features like SVG import/export and text wrapping
Code Comparison
Fabric.js:
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
});
canvas.add(rect);
Konva:
var stage = new Konva.Stage({
container: 'container',
width: 500,
height: 500
});
var layer = new Konva.Layer();
var rect = new Konva.Rect({
x: 100,
y: 100,
fill: 'red',
width: 20,
height: 20
});
layer.add(rect);
stage.add(layer);
Both libraries allow for easy creation and manipulation of shapes on an HTML5 canvas. Fabric.js uses a single canvas element, while Konva introduces the concept of stages and layers. Konva's approach can lead to better performance for complex scenes but may require a slight learning curve for developers familiar with traditional canvas manipulation.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
Pros of PixiJS
- Optimized for high-performance 2D rendering, especially for games and interactive graphics
- Extensive WebGL support with automatic fallback to Canvas
- Robust plugin ecosystem for additional functionality
Cons of PixiJS
- Steeper learning curve for developers new to WebGL concepts
- Less suited for complex vector graphics and object manipulation
- Limited built-in support for advanced text handling and typography
Code Comparison
PixiJS (creating a simple sprite):
const app = new PIXI.Application();
document.body.appendChild(app.view);
const sprite = PIXI.Sprite.from('image.png');
app.stage.addChild(sprite);
Fabric.js (creating a simple image object):
const canvas = new fabric.Canvas('canvas');
fabric.Image.fromURL('image.png', (img) => {
canvas.add(img);
canvas.renderAll();
});
Summary
PixiJS excels in high-performance 2D rendering, making it ideal for games and interactive graphics. It leverages WebGL extensively but may have a steeper learning curve. Fabric.js, on the other hand, is more suited for vector graphics and object manipulation, with easier learning for Canvas-based development. The choice between them depends on the specific requirements of your project, such as performance needs, graphic complexity, and developer expertise.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
Pros of EaselJS
- Better performance for complex animations and games
- Part of the larger CreateJS suite, offering integrated tools for sound, preloading, and tweening
- Stronger focus on canvas-based rendering and animation
Cons of EaselJS
- Less feature-rich for static image manipulation compared to Fabric.js
- Steeper learning curve, especially for developers new to canvas-based graphics
- Smaller community and fewer resources available online
Code Comparison
EaselJS:
var stage = new createjs.Stage("canvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.update();
Fabric.js:
var canvas = new fabric.Canvas('canvas');
var circle = new fabric.Circle({
radius: 50,
fill: 'red',
left: 100,
top: 100
});
canvas.add(circle);
Both libraries provide ways to create and manipulate canvas objects, but Fabric.js offers a more straightforward API for static elements, while EaselJS excels in animation-heavy scenarios. EaselJS uses a display list (stage and children), whereas Fabric.js treats the canvas as a collection of objects. The choice between them depends on the project's specific requirements and the developer's familiarity with each library's paradigms.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Pros of Paper.js
- More powerful vector graphics capabilities, including advanced path manipulation and boolean operations
- Built-in scene graph and layer management for complex drawings
- Extensive documentation and interactive examples
Cons of Paper.js
- Steeper learning curve due to its more complex API
- Smaller community and fewer third-party resources compared to Fabric.js
Code Comparison
Paper.js:
var path = new Path();
path.strokeColor = 'black';
path.moveTo(new Point(30, 75));
path.lineTo(new Point(30, 25));
path.lineTo(new Point(80, 25));
Fabric.js:
var canvas = new fabric.Canvas('canvas');
var path = new fabric.Path('M 30 75 L 30 25 L 80 25');
path.set({ fill: '', stroke: 'black', strokeWidth: 1 });
canvas.add(path);
Both libraries allow for creating and manipulating paths, but Paper.js offers a more object-oriented approach with its Point and Path classes, while Fabric.js uses a more concise string-based path definition and requires explicit canvas management.
Paper.js is generally better suited for complex vector graphics projects, while Fabric.js excels in interactive canvas applications and image manipulation tasks. The choice between the two depends on the specific requirements of your project and your familiarity with each library's paradigms.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
andSVG
i/o- Typed and modular
- Unit tested
Supported Browsers/Environments
Context | Supported Version | Notes |
---|---|---|
Firefox | âï¸ | 58 |
Safari | âï¸ | 11 |
Opera | âï¸ | chromium based |
Chrome | âï¸ | 64 |
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
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
// v6
import { Canvas, Rect } from 'fabric'; // browser
import { StaticCanvas, Rect } from 'fabric/node'; // node
// v5
import { fabric } from 'fabric';
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 * as fabric from 'fabric'; // v6
import { fabric } from 'fabric'; // v5
export const FabricJSCanvas = () => {
const canvasEl = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const options = { ... };
const canvas = new fabric.Canvas(canvasEl.current, options);
// make the fabric.Canvas instance available to your app
updateCanvasContext(canvas);
return () => {
updateCanvasContext(null);
canvas.dispose();
}
}, []);
return <canvas width="300" height="300" ref={canvasEl}/>;
};
Node.js
import http from 'http';
import * as fabric from 'fabric/node'; // v6
import { fabric } from 'fabric'; // v5
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`,
);
});
See our ready to use templates.
Other Solutions
Project | Description |
---|---|
Three.js | 3D graphics |
PixiJS | WebGL renderer |
Konva | Similar features |
html-to-image | HTML to image/canvas |
More Resources
- WIP new fabricjs.com
- Demos on
fabricjs.com
- Fabric.js on
Twitter
- Fabric.js on
CodeTriage
- Fabric.js on
Stack Overflow
- Fabric.js on
jsfiddle
- Fabric.js on
Codepen.io
Credits
- kangax
- asturur on
Twitter
- ShaMan123
- melchiar
- Ernest Delgado for the original idea of manipulating images on canvas
- Maxim "hakunin" Chernyak for ideas, and help with various parts of the library throughout its life
- Sergey Nisnevich for help with geometry logic
- Stefan Kienzle for help with bugs, features, documentation, GitHub issues
- Shutterstock for the time and resources invested in using and improving Fabric.js
- and all the other contributors
Top Related Projects
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser
Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
The HTML5 Creation Engine: Create beautiful digital content with the fastest, most flexible 2D WebGL renderer.
The Easel Javascript library provides a full, hierarchical display list, a core interaction model, and helper classes to make working with the HTML5 Canvas element much easier.
The Swiss Army Knife of Vector Graphics Scripting – Scriptographer ported to JavaScript and the browser, using HTML5 Canvas. Created by @lehni & @puckey
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot