How to use Fabric js Canvas.

1. Introduce

Fabric.js is a powerful JavaScript library that provides a framework for creating interactive and customizable HTML5 canvas applications. It simplifies the process of working with canvas elements by abstracting away some of the complexities involved in canvas manipulation. Fabric.js allows you to easily create and manipulate objects such as shapes, images, and text on a canvas, and provides support for interactivity, animation, and event handling.

2. Project Structure files

  • lib: contain fabric library
  • index.html. This is main html file for project
  • index.js This is js file include canvas function.
  • styles.css. This is styling file for project.

3. let start.

– Write html and add js, css file to html.

The first, you can go to the fabric website (fabricjs.com) and download fabric js library to the folder lib.

Next, you can link js and css files to html

add console.log(“here is index.js”) to the index.js and check in console to make sure that you add file Js successfully

– Initialize Canvas. To Initialize Canvas, You need initialize canvas element in in html and create canvas call the canvas element in js file.

// index.html
<canvas id="my-canvas"></canvas>
//index.js
var canvas = new fabric.Canvas('my-canvas');

// Optionally, set canvas properties
canvas.backgroundColor = '#ccc'; 
canvas.setWidth(600); // set width
canvas.setHeight(600); // set height

For now, We have a simple canvas with background is #ccc, and size is 600 x 600 px

– Add Text to Canvas. Fabric js provide a method Fabric.Text() to add to canvas.

// index.js
// add text 
var text = new fabric.Text('Hello, Fabric.js!', {
    left: 100,
    top: 100,
    fill: 'red',
    fontFamily: 'Arial',
    fontSize: 30
});

// Add the Text object to the canvas
canvas.add(text);

This is Result.

– Add Image to Canvas, You can use function fabric.Image.fromURL() to add image to canvas.

index.js
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
    // Create a Fabric.js Image object
    var image = img.set({
        left: 100,
        top: 150,
        scaleX: 0.5, // Scale the image if needed
        scaleY: 0.5
    });

    // Add the Image object to the canvas
    canvas.add(image);

and here is Result:

– Add Rect to Canvas, You can use function fabric.Rect() to add Rect to canvas //

//index.js
var rect = new fabric.Rect({
    left: 300,
    top: 300,
    width: 200,
    height: 100,
    fill: 'green'
});
canvas.add(rect);

And this is result

Conclusion: Here are simple examples about fabric js, with fabric you can make more advance function for custom design on website. The fabric js is applied for a lot of design tool on the website. APB product labels is a Shopify app use Fabric js to Allow Merchant custom Create and customize label.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top