Canvas Utility Library Fabric.js Manual

Posted by guttyguppy on Fri, 10 May 2019 21:12:38 +0200

brief introduction

What is Fabric.js?

Fabric.js is a library that can simplify Canvas programming. Fabric.js provides Canvas with the missing object model, svg parser, interaction and a set of other indispensable tools. Because Fabric. JS is a foreign framework, the official API is messy and numerous, most of the relevant documents are English documents, and the number is not large, so this paper aims to help novices quickly start Fabric. JS in the project and enjoy the process of drawing Canvas.

Why use Fabric.js?

Canvas provides a good canvas capability, but Api is not friendly enough. Drawing simple graphics is actually OK, but it is not so convenient to do some complex graphics drawing and compile some complex effects. Fabric.js is developed for this purpose. It mainly writes code in the way of objects.

What Fabric.js can do

  • Create and fill graphics on Canvas (including pictures, text, regular graphics and complex path composition graphics).
  • Fill the graphics with gradient colors.
  • Composite graphics (including composite graphics, graphics, text, pictures, etc.).
  • Set up graphics animation set user interaction.
  • Generate JSON, SVG data, etc.
  • Generate Canvas objects with drag and drop functionality.

start

Introducing Fabric.js into the Vue project

Assuming that ES6 and Webpack are being used in your project, you can start using Fabric.js as follows:

1. On the command line:

              npm install fabric(or yarn add fabric)

2. Introduce it into. vue file

              import { fabric } from 'fabric'

3. mounted in a single file of. vue: Start your Fabric.js journey in the life cycle

Note: The default fabric npm module generates quite a large package. If you have many packages in Fabric.js that you may not need, in this case, you can build your own version here or on the command line.

Drawing graphics

Drawing Regular Graphics

1. Statement Canvas

       var canvas =new fabric.Canvas('main');

2. Drawing Graphics

       var rect = new fabric.Rect({

           left:100,//The distance to the left of the canvas in pixels

           top:100,//Distance from the top of the canvas

           fill:'red',//Filled color

           width:30,//The width of a square

          height:30//The Height of a Square

       });

3. Add graphics to canvas

       canvas.add(rect);

Other regular graphics:

  • Draw a square var rect = new fabric.Rect
  • Draw a circle var circle = new fabric.Circle
  • Draw a triangle var triangle = new fabric.Triangle

Drawing irregular figures

Use Path Mapping: Drawing by moving points and lines. Through the application of lines, curves and arcs, very complex graphics are drawn.

In fabric.Path() method, "M" stands for "move" command, and "M 00" stands for moving the brush to (0,0) point coordinates.

"L" stands for "line" and "L 200 100" means to draw a line with a pen from (0,0) coordinates to (200,100) coordinates. "z" means to close the path of the graph.

After drawing the triangle, we can use the set() method to set the position, color, angle, transparency and other attributes of the triangle.

The code is as follows:

       var path = new fabric.Path('M 0 0 L 200 100 L 170 200 z');

       path.set({ left: 120, top: 120,fill:'red' });

       canvas.add(path);

Operation of Pictures

HTML Insert Pictures

       <body>
           <canvas id="canvas" width='800' height='800'></canvas>
           <img src="./2.png" id="img">
       </body>
       ---------------------
       var canvas = new fabric.Canvas('canvas');//Statement canvas
       var imgElement = document.getElementById('img');//Declare our pictures     
       var imgInstance = new fabric.Image(imgElement,{  //Set the position and appearance of the picture
            left:100,
            top:100,
            width:200,
            height:100,
            angle:30//Setting Clockwise Rotation Angle of Graphics
       });
      
       canvas.add(imgInstance);//Add to canvas

JavaScript Insert Pictures

       var canvas = new fabric.Canvas('canvas');
           fabric.Image.fromURL('./2.png', function(oImg) {
           oImg.scale(0.1);//The picture shrunk 10 times
           canvas.add(oImg);
       }); 

interactive

Interaction with Canvas

       canvas.add(imgInstance);//Add to canvas
       var canvas = new fabric.Canvas('canvas');
       canvas.on('mouse:down', function(options) {
           console.log(options.e.clientX, options.e.clientY)
       })

Note: Common monitoring incidents are as follows:

  • mouse:down: when the mouse is pressed
  • mouse:move: when the mouse moves
  • mouse:up: When the mouse is raised

Operation of objects on canvas

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

       var rect = new fabric.Rect({ width: 100, height: 50, fill: 'green' });

       rect.on('selected', function() {//Select the listening event

           console.log('selected a rectangle');

       });

 

       var circle = new fabric.Circle({ radius: 75, fill: 'blue' });

       circle.on('selected', function() {

           console.log('selected a circle');

       });

       canvas.add(rect);

       canvas.add(circle);

Note: Common monitoring events are as follows:

  • after:render: After redrawing the canvas
  • object:selected: The object is selected
  • Object: move: object movement
  • object:rotating: Objects are rotated
  • object:added: Objects are added
  • object:removed: Object is removed

combination

new fabric.Group(): Accepts two parameters: an array of object names to be combined, and a common property of objects to be combined.

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

        var circle = new fabric.Circle({//Draw circles

        radius: 100,

        fill: '#f00',

        scaleY: 0.5,

        originX: 'center',//Adjust the X-axis coordinates of the center point

        originY: 'center'//Adjusting the Y-axis coordinates of the center point

      });

     var text = new fabric.Text('Hello World', {//Draw text

       fontSize: 30,

       originX: 'center',

       originY: 'center'

    })

    //Combination

    var group = new fabric.Group([circle, text], {

      left: 150,

      top: 100,

      angle: 10

    })

    canvas.add(group);

Serializable and Deserialize

serialize

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

    var rect = new fabric.Rect({

        width: 100,

        height: 100,

        fill: 'red'

    });

    canvas.add(rect);
    
    console.log(JSON.stringify(canvas.toJSON()));

Deserialize

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

    canvas.loadFromJSON('{"objects":[{"type":"rect","left":50,"top":50,"width":20,"height":20,"fill":"green","overlayFill":null}')

SVG

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

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

    canvas.add(rect);

    canvas.toSVG();

Reference documents: http://fabricjs.com/articles/

Topics: Javascript Vue JSON npm Programming