简体   繁体   English

使用fabricjs从Canvas中删除所有对象(Grouped / Ungrouped)

[英]Deleting All objects(Grouped/Ungrouped) from Canvas with fabricjs

I am trying to remove all the objects on my Canvas without selecting them. 我试图删除我的画布上的所有对象而不选择它们。 The objects in the Canvas include Grouped and Ungrouped object. Canvas中的对象包括Grouped和Ungrouped对象。 All the Examples I've seen demonstrate how to delete a single ungroup object. 我见过的所有示例都演示了如何删除单个ungroup对象。

Canvas.ForEachObject(function(o){
     o.remove();
    });

Please see the fiddle for an example of what I'm trying to achieve. 请查看小提琴,了解我正在努力实现的目标。 https://jsfiddle.net/Shane00711/r8su3ya0/ https://jsfiddle.net/Shane00711/r8su3ya0/

Did you know that canvas.remove can take more than one parameter? 你知道canvas.remove可以使用多个参数吗? So the easiest way should be this one: 所以最简单的方法应该是这个:

canvas.remove(...canvas.getObjects());

Other than canvas.clear this will only remove the objects in the canvas and not also the background. 除canvas.clear之外,这只会删除画布中的对象而不是背景。

You just need to call 你只需要打电话

canvas.clear()

it will remove all object 它将删除所有对象

I figured out what I need to do in order to delete every object(grouped/ungrouped) from my Canvas. 我弄清楚我需要做什么才能从我的Canvas中删除每个对象(分组/未分组)。 First I had to get all the objects in the canvas. 首先,我必须得到画布中的所有对象。

var obj = canvas.getObjects();

once I got all the objects I simply had to loop through them removing each one as I did. 一旦我得到了所有的物体,我只需要循环通过它们就像我一样去除每一个物体。

canvas.remove(obj[0]).

The reason I reference the index 0 in my 我在我的引用索引0的原因

canvas.remove(obj[0]) 

is because every time and object was removed from the canvas the number of object in the list 'obj' also decreased by 1, moving all the objects up by 1 index. 是因为每次从画布中删除对象时,列表'obj'中的对象数量也减少1,将所有对象向上移动1个索引。 which meant that every object on my canvas would at some point be at index 0 of the 'obj' list. 这意味着我画布上的每个对象都会在某个时刻位于'obj'列表的索引0处。

here's a fiddle of a working example. 这是一个工作实例的小提琴。 where I delete all objects on the canvas without selecting a single one. 我删除画布上的所有对象而不选择单个对象。 http://jsfiddle.net/Shane00711/r8su3ya0/8/ http://jsfiddle.net/Shane00711/r8su3ya0/8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM