所以我正在尝试为我的应用程序实现撤消功能并且我遇到了一个问题,撤消功能可以工作,但是所有这些都是canvas.remove()无法正常工作由于某种原因或对象:删除事件不触发。确保对象确实存在我console.log它确定它确实存在..但结构js不会删除对象,也不会触发对象:删除(显然)
canvas.on('object:added',function(){
h = [];
});
function undo(){
if(canvas._objects.length>0){
console.log(h);
h.push(canvas._objects.pop());
var lastItem = h[h.length - 1];
//Logs the object - check the screenshot
console.log(lastItem);
canvas.remove(lastItem);
canvas.renderAll();
}
}
$("#undo").click(function()
{
undo();
});
//Not firing even though i removed the object..
canvas.on('object:removed',function(object)
{
console.warn(object);
});
答案 0 :(得分:1)
如果您要使用canvas.remove()
删除对象,则只会触发'object:removed'
事件。
<强> 样本 强>
var canvas = new fabric.Canvas('canvas');
canvas.add(new fabric.Circle({
left:50,top:50,radius:50,fill:'red'
}))
canvas.add(new fabric.Circle({
left:150,top:150,radius:50,fill:'green'
}))
canvas.add(new fabric.Circle({
left:250,top:250,radius:50,fill:'blue'
}))
canvas.add(new fabric.Rect({
left:250,top:150,width:100,height:100
}));
canvas.requestRenderAll();
function undo(){
var object = canvas.item(canvas.getObjects().length-1);
canvas.remove(object);
}
canvas.on('object:removed',function(object){
console.warn(object);
})
&#13;
canvas{
border:2px solid #000;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick='undo()'>undo</button>
<canvas id='canvas' width=500 height=400>
&#13;
答案 1 :(得分:0)
这将为您工作:
var objects = canvas.getObjects();
for(var i = 0; i < objects.length; i++){
//console.log(objects[i]);
canvas.remove(objects[i]);
}canvas.renderAll();