嗨,我想使用FabricJS在元素中添加删除按钮.我有一个例子:
我尝试添加这部分代码但是当我调整图像大小时,删除按钮不会保留在原位.
http://jsfiddle.net/wxao1on8/13/
function addDeleteBtn(x,y,w){ $(".deleteBtn").remove(); var btnLeft = x; var btnTop = y - 30; var widthadjust=w/2; btnLeft=widthadjust+btnLeft-1 var deleteBtn = '<img src="https://www.funagain.com/images/old/common/delete-icon.png" class="deleteBtn" ' + 'style="position:absolute;top:'+btnTop+'px;right:'+btnLeft+'px;cursor:pointer;"/>'; $(".canvas-container").append(deleteBtn); } canvas.on('object:selected',function(e){ addDeleteBtn(e.target.oCoords.mt.x,e.target.oCoords.mt.y,e.target.width); }); canvas.on('mouse:down',function(e){ if(!canvas.getActiveObject()) { $(".deleteBtn").remove(); } }); canvas.on('object:modified',e.target.width); }); canvas.on('object:moving',function(e){ $(".deleteBtn").remove(); }); $(document).on('click',".deleteBtn",function(){ if(canvas.getActiveObject()) { canvas.remove(canvas.getActiveObject()); $(".deleteBtn").remove(); } });
解决方法
target.oCoords.mt是中上角.
请改用右上角:e.target.oCoords.tr
var canvas = new fabric.Canvas('canvas'); var HideControls = { 'tl':true,'tr':false,'bl':true,'br':true,'ml':true,'mt':true,'mr':true,'mb':true,'mtr':true }; fabric.Image.fromURL('http://serio.piiym.net/CVBla/txtboard/thumb/1260285874089s.jpg',function (img) { img.top = 60; img.left = 30; img.setControlsVisibility(HideControls); canvas.add(img); }); canvas.renderAll(); function addDeleteBtn(x,y){ $(".deleteBtn").remove(); var btnLeft = x-10; var btnTop = y-10; var deleteBtn = '<img src="https://www.funagain.com/images/old/common/delete-icon.png" class="deleteBtn" style="position:absolute;top:'+btnTop+'px;left:'+btnLeft+'px;cursor:pointer;width:20px;height:20px;"/>'; $(".canvas-container").append(deleteBtn); } canvas.on('object:selected',function(e){ addDeleteBtn(e.target.oCoords.tr.x,e.target.oCoords.tr.y); }); canvas.on('mouse:down',function(e){ if(!canvas.getActiveObject()) { $(".deleteBtn").remove(); } }); canvas.on('object:modified',function(e){ addDeleteBtn(e.target.oCoords.tr.x,e.target.oCoords.tr.y); }); canvas.on('object:scaling',function(e){ $(".deleteBtn").remove(); }); canvas.on('object:moving',function(e){ $(".deleteBtn").remove(); }); canvas.on('object:rotating',function(e){ $(".deleteBtn").remove(); }); $(document).on('click',function(){ if(canvas.getActiveObject()) { canvas.remove(canvas.getActiveObject()); $(".deleteBtn").remove(); } });