fabricjs相關方法知識點


1: 獲得畫布上的所有對象:

var items = canvas.getObjects();

2: 設置畫布上的某個對象為活動對象。

canvas.setActiveObject(items[i]);

3:獲得畫布上的活動對象

canvas.getActiveObject();

4:取消畫布中的所有對象的選中狀態。

canvas.discardActiveObject(); // 如果這樣不生效,可以使用 canvas.discardActiveObject().renderAll();

5: 設置畫布中的對象的某個屬性值,比如第 0 個對象的 id

var items = canvas.getObjects();
tems[0].id ="items_id0" 或 items[0].set("id","items_id0")

6:獲得畫布中對象的某個屬性,比如 第0 個對象的 id

var items = canvas.getObjects();
items[0].id;
或
items[0].get("id");

7: 重新渲染一遍畫布,當畫布中的對象有變更,在最后顯示的時候,需要執行一次該操作

canvas.renderAll();

8: 清除畫布中所有對象:

canvas.clear();

9:清除畫布中的活動對象:

var t = canvas.getActiveObject();
t && canvas.remove(t);

10: 設置活動對象在畫布中的層級

var t = canvas.getActiveObject();
canvas.sendBackwards(t) //向下跳一層
canvas.sendToBack(t) //向下跳底層:
canvas.bringForward(t) //向上跳一層:
canvas.bringToFront(t) //向上跳頂層:
或者:
t.sendBackwards();
t.sendToBack();
t.bringForward();
t.bringToFront();

11:加載圖片時圖片縮放到指定的大小。

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);
});

12:當選擇畫布中的對象時,該對象不出現在頂層。

canvas.preserveObjectStacking = true; // 選中對象不會到最高層,按原層次擺放

13:為畫布通過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));
});        

14: originx: originy:代表坐標系。

15: 畫布對象居中設置:

var t = canvas.getActiveObject();
t.center(); //全部居中
t.centerH(); //水平居中
t.centerV(); //垂直居中
t.setCoords(); //注:必須設coords以上設置才會有效。

16: 當對象移動時 限制對象的 不超出畫布

// 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);
  }
}

17:當畫布對象放大時限制其操出邊界:

//注意當創建對象到畫布上時必須先加上:
obj.saveState();
//在對象修改時方法里就可以調用了。
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();
  }
}

18:當生成json對象時,背景圖片顯示出來。

fabric.Image.fromURL( bgImg, function(oImg) {
  oImg.set({
    width: 400,
    height:400,
    left:0,
    top:0,
    originX: 'left',
    originY: 'top',
    opacity:0
  });
  //當toObject方法時顯示背景圖片。
  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' });

19:創建蒙版層

//獲取蒙版位置屬性(非必要):
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"));
//創建蒙版
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();
} 
//調用的地方:
//文字層設置蒙版
  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) 
   }
});
// 圖片層設置蒙版:
// 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) 
        }

    });

    //生成的圖片縮放到指定的尺寸。
    oImg.scaleToWidth(image_width);
    oImg.scaleToHeight(image_height);

    //to object 時添加 id屬性。添加自定義屬性
    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();   

 20保存、撤銷、重做

this.state = {
    saveLen: 0,
    delLen: 0,
    operIndex: -1,
    saveOperateList: [],
    deleteOperateList: [],
}
// 操作保存的數據
  operateData = () => {
    const { canvas, delLen, saveLen, deleteOperateList, saveOperateList, operIndex } = this.state;
    let delList = [...deleteOperateList];
    let saveList = [...saveOperateList];
    let operindex = operIndex;
    const json = canvas.toJSON();
    if (delLen > 0) {
        //delList.some(item => {
         // saveList[item].del = true;
        //})  
       // saveList = saveList.filter(item => {
          //return !item.del;
       // })
        delList = [];
        saveList.push(json);
        operindex = saveList.length - 1;
    } else {
      saveList.push(json);
      operindex += 1;
    }
    this.setState({
      saveOperateList: saveList,
      deleteOperateList: delList,
      delLen: delList.length,
      saveLen: saveList.length,
      operIndex: operindex
    })
  }
  // 上一步
  prevStepOperate = () => {
    const { canvas, delLen, saveLen, deleteOperateList, saveOperateList, operIndex } = this.state;
    let delList = [...deleteOperateList];
    let saveList = [...saveOperateList];
    let operindex = operIndex;
    if (operindex > 0) {
      canvas.loadFromJSON(saveList[operindex - 1]).renderAll();
      if (delList.includes(operindex - 1)) {
      } else {
        delList.push(operindex);
        operindex -= 1;
      }
    }
    this.setState({
      saveOperateList: [...saveList],
      deleteOperateList: [...delList],
      delLen: delList.length,
      saveLen: saveList.length,
      operIndex: operindex
    })
  }
  // 下一步
  nextStepOperate = () => {
    const { canvas, delLen, saveLen, deleteOperateList, saveOperateList, operIndex } = this.state;
    let delList = [...deleteOperateList];
    let saveList = [...saveOperateList];
    let operindex = operIndex;
    if (operindex + 1 >= saveList.length) {
      return;
    }
    canvas.loadFromJSON(saveList[operindex + 1]).renderAll();
    if (delList.includes(operindex + 1)) {
        const index = delList.indexOf(operindex + 1);
        delList.splice(index, 1);
    } else {
    }
    operindex = operindex + 1;
    this.setState({
      saveOperateList: [...saveList],
      deleteOperateList: [...delList],
      delLen: delList.length,
      saveLen: saveList.length,
      operIndex: operindex
    })
  }

21fabric.js添加自定義屬性且不丟失

// 添加圖片到canvas
  addImgInstance = (target, scale, id) => {
    const { canvas } = this.state;
    let imgInstance = new fabric.Image(target, {
      left: 0,
      top: 0,
      scaleX: scale.x,
      scaleY: scale.y,
      id: id, // 添加自定義屬性
    });
    // 添加自定義屬性
    imgInstance.toObject = (function(toObject) {
      return function() {
        return fabric.util.object.extend(toObject.call(this), {
          id: id,
        });
      };
    })(imgInstance.toObject);
    canvas.add(imgInstance);
}

22fabric.js轉化對象時保存自定義屬性(重新回到頁面時會丟失,需要在toJSON時做處理)

canvas.toJSON(['id']); // id是需要保存的屬性
canvas.toJSON(['id', 'id2']); // 保存多個屬性

 

參考文章:關於fabric.js的使用經驗積累


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM