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的使用经验积累