Introduction to the

Fabric.js is a library that simplifies writing Canvas programs. Fabric.js provides Canvas’s missing object model, SVG Parser, interaction, and a whole set of other indispensable tools. Fabric.js can do a number of things, as follows:

  • Create and fill graphics (including pictures, text, regular graphics and complex path composition graphics) on the Canvas.
  • Fill the shape with a gradient color.
  • Combined graphics (including combined graphics, graphic text, pictures, etc.).
  • Set up graphical animation set user interaction.
  • Generate JSON, SVG data, etc.
  • Generating Canvas objects comes with drag-and-drop functionality.

Using the tutorial

The installation

NPM install

npm install fabric --save
Copy the code

CDN reference

<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.6/fabric.min.js"></script>//Copy the code

Can be found at https://www.bootcdn.cn/fabric.js/ faster source of CDN

Before using, take a look at the overall effect I made as follows:

Initialize the

Create a basic canvas

<canvas id="canvas" width="350" height="200"></canvas>
const card = new fabric.Canvas('canvas') / /... // If the <canvas> tag does not set the width and height, you can use js to dynamically set card.setwidth (350) card.setheight (200).Copy the code

Interaction with the canvas

Common listening events are as follows:

  • Mouse :down: when the mouse is pressed down
  • Mouse :move: when the mouse moves
  • Mouse :up: indicates that the mouse is up
    var canvas = new fabric.Canvas('canvas');
    canvas.on('mouse:down'.function(options) {
        console.log(options.e.clientX, options.e.clientY)
    })
Copy the code

Listen for canvas object events for “next step” divine action

The following are common events:

  • Object: Added Adds a layer
  • Object: Modified Edits a layer
  • Object :removed Layer
  • Selection: creates the first selected layer
  • Selection: Updated layer selection changes
  • Selection: Cleared Layer selected

Here is the transcript, with more reference to the __fabricjs official website event __ :

So which other events are available in Fabric? Well, from mouse-level ones there are “mouse:down”, “mouse:move”, and “mouse:up”. From generic ones, there are “after:render”. Then there are selection-related events: “before:selection:cleared”, “selection:created”, “selection:cleared”. And finally, object ones: “object:modified”, “object:selected”, “object:moving”, “object:scaling”, “object:rotating”, “object:added”, and “object:removed”

Setting the canvas background

// Set the canvas background to fabric.image.fromurl ('xx/xx/bg.jpg'ScaleX: card.width/img.width, scaleY: => {img. Set ({// set the size of the image by scale. card.height / img.height, }); // set background card.setBackgroundimage (img, card.renderall. bind(card)); card.renderAll(); });Copy the code

Add a layer object to the canvas

Fabric.js provides many objects. In addition to the basic Rect, Circle, Line, Ellipse, Polygon, Polyline, Triangle objects, there are more advanced objects such as Image, Textbox, Group, etc. These are objects that inherit from Fabric.

/** * How do I add an Image object to the canvas? */ // const imgElement = document.getelementById ('my-image'); Const imgInstance = new fabric.Image(imgElement, {left: 100, // Image relative to canvas top: 100, // Image relative to canvas top: 100, // Image relative to canvas top: 100, // Image relative to canvas top: 100, // Image relative to canvas top: 100, // Image relative to canvas top: ScaleX: 0; scaleY: 0; scaleX: 0; scaleX: 0; scaleY: 0; scaleX: 0; // Add the object card.add(imgInstance);Copy the code
/** * How do I add a Textbox object to the canvas? */ const textbox = new fabric.Textbox('This is a text.', {left: 50, top: 50, width: 150, fontSize: 20, // fontSize fontWeight: 800, // fontSize // fill:'red'// font color // fontStyle:'italic', // italic // fontFamily:'Delicious', // Set the font // stroke:'green', // stroke color // strokeWidth: 3, // strokeWidth hasControls:false,
    borderColor: 'orange',
    editingBorderColor: 'blue'// Click the text to enter the edit state border color}); Card.add (textbox);Copy the code

Gets the currently selected layer object

This.selectedobj = card.getActiveObject(); // Return the selected layer in the current canvas.'selection:created', (e) => {// Select layer event when dynamic update assignment this.selectedobj = e.target})Copy the code

Normal operation

this.selectedObj.rotate(angle); // Rotate the layer this.selectedobj.set ({scaleX: – this. SelectedObj. ScaleX, / / flip horizontal}) card. Remove (enclosing selectedObj) / / incoming need to remove the object of this. SelectedObj. BringForward (); / / up layer enclosing selectedObj. SendBackwards (); // Move down the layer card.moveto (object, index); // You can also move the layer to the specified position using the canvas object’s moveTo method

// Call card.renderAll() after all layers.

The size of photo taken in mobile phone album is too large, causing drag trouble

When adding a picture object, there are two parameters that can be applied, namely, scaleX and scaleY parameters. By these two parameters, the size of the picture can be scaled correspondingly, which is convenient for the picture to be fully reflected on the canvas.

First, the mobile phone picture is loaded, calculate the width and height, according to their canvas vertical and horizontal contrast to calculate the picture zoom parameters can be.

          new Promise(function(res,rej){
              let img = new Image();
              img.onload = function(){
                 console.log(img.width,img.height);
                 res([img.width,img.height]);
              }
              img.src = file.content;
          }).then(function(response){
              let width = response[0];
              let height = response[1];
              letXYRet = 0.61; //300/490 vertical and horizontal comparisonslet targetRepix = 1;

              if(height > 490)
              {
                targetRepix = (490/height).toFixed(2);
              }

              if(width > 300)
              {
                targetRepix = (300/width).toFixed(2);
              }


              fabric.Image.fromURL(file.content, (img) => {
                  img.set({
                      top:30,
                      left:30,
                      scaleX: targetRepix, 
                      scaleY: targetRepix,
                      hasControls: true// Enable the layer control borderColor:'orange', // Layer control border color}); Card.add (img); }); })Copy the code

Text thickness and color are optional

// where selectedObj is the currently selected text object

This.selectedobj.set ({fontWeight: XXX // change the weight}); This.selectedobj.set ({fill: XXX // change color});Copy the code

Changes the box style of the selected object

        card.on('selection:updated', (e) => {
          console.log('selection:updated', e.target) this.setSelectedobj (e.target) // Change the style with the selected object.false,
                cornerColor: 'blue',
                cornerStrokeColor: 'red',
                borderColor: 'red',
                cornerSize: 12,
                padding: 10,
                cornerStyle: 'circle',
                borderDashArray: [3, 3]
            });

        })
Copy the code

The effect is shown below:

Canvas serialization and deserialization ———— record state records

The framework provides methods such as toJSON and loadFromJSON, which export the JSON information of the current canvas and load the JSON canvas information to restore the state of the canvas.

Const currState = card.tojson (); Card.loadfromjson (lastState, () => {card.renderAll(); });Copy the code

Export the canvas as an image

const dataURL = card.toDataURL({
  format: 'jpeg'//left: 100, //top: 100, //width: 200, //height: 200});Copy the code