Detailed explanation of how to use the canvas operation plugin fabric.js

Detailed explanation of how to use the canvas operation plugin fabric.js

Fabric.js is a very useful canvas operation plug-in. Here are some knowledge points used in daily projects:

//1: Get all objects on the canvas:
var items = canvas.getObjects();

//2: Set an object on the canvas as the active object.
canvas.setActiveObject(items[i]);

//3: Get the active object on the canvas canvas.getActiveObject()

//4: Cancel the selection of all objects in the canvas.
canvas.discardActiveObject();

//5: Set a property value of an object in the canvas, such as the ID of the 0th object
var items = canvas.getObjects();
items[0].id = "items_id0" or items[0].set("id","items_id0")

//6: Get a property of an object in the canvas, such as the ID of the 0th object
var items = canvas.getObjects();
items[0].id;
//or items[0].get("id");

//7: Re-render the canvas. When the objects in the canvas are changed, this operation needs to be performed once at the last display. canvas.renderAll()

//8: Clear all objects in the canvas:
canvas.clear();

//9: Clear the active object in the canvas:
 var t = canvas.getActiveObject();
 t && canvas.remove(t);

//10: Set the level of the active object in the canvas var t = canvas.getActiveObject();
canvas.sendBackwards(t) //jump down one layer canvas.sendToBack(t) //jump down to the bottom layer:
canvas.bringForward(t) //jump up one level:
canvas.bringToFront(t) // Jump to the top layer:
//or:
t.sendBackwards();
t.sendToBack();
t.bringForward();
t.bringToFront();

//10: When loading an image, scale the image to the specified size.
fabric.Image.fromURL(image_src, function(oImg) {
  oImg.set({
    left:tmp_left,
    top:tmp_top,
    centeredScaling:true,
    cornerSize: 7,
    cornerColor: "#9cb8ee",
    transparentCorners: false,
  });
  oImg.scaleToWidth(image_width);
  oImg.scaleToHeight(image_height);
  canvas.add(oImg).setActiveObject(oImg);
 });

//11: When an object in the canvas is selected, the object does not appear on the top layer.
canvas.preserveObjectStacking = true;

// 12: Add a background image to the canvas via URL var bg_url = "http://www.xxxx.com/...../bg.png"      
fabric.Image.fromURL( bg_url , function(oImg) {
  oImg.set({
  width: canvas_obj.width, 
  height: canvas_obj.height,
  originX: 'left', 
  originY: 'top'
  });
  canvas_obj.setBackgroundImage(oImg, canvas_obj.renderAll.bind(canvas_obj));
});

//13: originx: originy: represents the coordinate system. 

//14: Center the canvas object:
var t = canvas.getActiveObject();
t.center(); //Center all t.centerH(); //Horizontal center t.centerV(); //Vertical center t.setCoords(); //Note: coords must be set for the above settings to be effective.

//15: When the object moves, limit the object to not exceed the canvas // canvas moving limit 
function objectMoving(e){
  var obj = e.target;
  if (obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width) {
      return;
   }    
   obj.setCoords();    
    // top-left corner
    if (obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
      obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
      obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
     }
     //bot-right corner
     if(obj.getBoundingRect().top+obj.getBoundingRect().height > obj.canvas.height 
     || obj.getBoundingRect().left + obj.getBoundingRect().width > obj.canvas.width){
      obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
         obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
      }
}

//16: When the canvas object is enlarged, limit its operation beyond the boundary:
//Note that when creating an object on the canvas, you must first add:
 obj.saveState();
 //The method can be called when the object is modified.
 function objectModified (e) {
  let obj = e.target;
  let boundingRect = obj.getBoundingRect(true);
  if (boundingRect.left < 0
    || boundingRect.top < 0
    || boundingRect.left + boundingRect.width > obj.canvas.getWidth()
    || boundingRect.top + boundingRect.height > obj.canvas.getHeight()) {
    obj.top = obj._stateProperties.top;
    obj.left = obj._stateProperties.left;
    obj.angle = obj._stateProperties.angle;
    obj.scaleX = obj._stateProperties.scaleX;
    obj.scaleY = obj._stateProperties.scaleY;
    obj.setCoords();
    obj.saveState();
  }else{
  obj.saveState();
}
  }
//17: When the json object is generated, the background image is displayed.
fabric.Image.fromURL( bgImg, function(oImg) {
   oImg.set({
     width: 400,
     height:400,
     left:0,
     top:0,
     originX: 'left',
     originY: 'top',
     opacity:0
   });
   //When toObject method is used, the background image is displayed.
   oImg.toObject = (function(toObject) {
     return function() {
      return fabric.util.object.extend(toObject.call(this), {
        opacity:1
      });
     };
  })(oImg.toObject); 

 canvas_obj.setBackgroundImage(oImg, canvas_obj.renderAll.bind(canvas_obj));  
}, { crossOrigin: 'Anonymous' });

//18: Create a mask layer //Get the mask position properties (optional):
var maskLayerTop = parseInt($(this).attr("data-top"));
var maskLayerLeft = parseInt($(this).attr("data-left"));
var maskLayerWidth = parseInt($(this).attr("data-width"));
var maskLayerHeight = parseInt($(this).attr("data-height"));
//Create a mask var clipMask = new fabric.Rect({
  originX: 'left',
  originY: 'top',
  left: maskLayerLeft,
  top: maskLayerTop,
  width: maskLayerWidth,
  height: maskLayerHeight,
  fill: 'rgba(0,0,0,0)', 
  strokeWidth:0,
  selectable: false
});  

clipMask.set({
  clipFor: 'pug'
});

canvas_obj.add(clipMask);                
function degToRad(degrees) {
  return degrees * (Math.PI / 180);
}   

function findByClipName(name){
  return _(canvas_obj.getObjects()).where({
    clipFor: name
  }).first()
}  

canvas_obj.clipByName = function(ctx) {
  this.setCoords();
  var clipObj = findByClipName(this.clipName);
  var scaleXTo1 = (1 / this.scaleX);
  var scaleYTo1 = (1 / this.scaleY);
  var skewXReverse = - this.skewX;
  var skewYReverse = - this.skewY;
  ctx.save();                  
  var ctxLeft = -( this.width / 2 ) + clipObj.strokeWidth;
    var ctxTop = -( this.height / 2 ) + clipObj.strokeWidth;
    var ctxWidth = clipObj.width - clipObj.strokeWidth;
    var ctxHeight = clipObj.height - clipObj.strokeWidth;
  ctx.translate( ctxLeft, ctxTop );
  ctx.scale(scaleXTo1, scaleYTo1);
  ctx.transform(1, skewXReverse, skewYReverse, 1, 0, 0);
  ctx.rotate(degToRad(this.angle * -1));                  
  ctx.beginPath();                  
  ctx.rect(
    clipObj.left - this.oCoords.tl.x,
    clipObj.top - this.oCoords.tl.y,
    clipObj.width,
    clipObj.height
  );
  ctx.closePath();                  
  ctx.restore();
} 
//Where to call:
//Set the mask for the text layer var t = new fabric.Text("Your Text", {
      id: first_level+"-text-input"+unique_id,
      cornerSize: 7,
      cornerColor: "#9cb8ee",
      transparentCorners: false,
      textAlign:"center",
      clipName: 'pug',
      clipTo: function(ctx) { 
      return _.bind(tmp_canvas_obj.clipByName, t)(ctx) 
      }
});
// Set the mask for the image layer:
// add the forntimage to the canvas
fabric.Image.fromURL(image_src, function(oImg) {
  oImg.set({
    id:first_level+"-image-input"+unique_id,
    left:tmp_left,
    top:tmp_top,
    centeredScaling:true,
    cornerSize: 7,
    cornerColor: "#9cb8ee",
    transparentCorners: false,
    clipName: 'pug',
    clipTo: function(ctx) { 
      return _.bind(tmp_canvas_obj.clipByName, oImg)(ctx) 
    }

  });

//19: The generated image is scaled to the specified size.
  oImg.scaleToWidth(image_width);
  oImg.scaleToHeight(image_height);

//20: Add id attribute when to object.
  oImg.toObject = (function(toObject) {
       return function() {
        return fabric.util.object.extend(toObject.call(this), {
         id: this.id,
        });
       };
  })(oImg.toObject);
  oImg.id = first_level+"-image-input"+unique_id;               
  oImg.saveState();
  tmp_canvas_obj.add(oImg).setActiveObject(oImg);
}, { crossOrigin: 'Anonymous' });
tmp_canvas_obj.renderAll();

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Fabric.js implements DIY postcard function

<<:  How to install mysql5.6 in docker under ubuntu

>>:  Detailed explanation of the available environment variables in Docker Compose

Recommend

How to set default value for datetime type in MySQL

I encountered a problem when modifying the defaul...

How to use union all in MySQL to get the union sort

Sometimes in a project, due to some irreversible ...

CSS overflow-wrap new property value anywhere usage

1. First, understand the overflow-wrap attribute ...

Detailed explanation of how to use the canvas operation plugin fabric.js

Fabric.js is a very useful canvas operation plug-...

CSS3 simple cutting carousel picture implementation code

Implementation ideas First, create a parent conta...

Element sample code to implement dynamic table

Table of contents 【Code background】 【Code Impleme...

Tutorial on building file sharing service Samba under CentOS6.5

Samba Services: This content is for reference of ...

Summary of Vue first screen performance optimization component knowledge points

Vue first screen performance optimization compone...

Full analysis of MySQL INT type

Preface: Integer is one of the most commonly used...

How to set the default value of a MySQL field

Table of contents Preface: 1. Default value relat...

js implements single click to modify the table

Pure js implements a single-click editable table ...