[英]Select all text objects on a Fabric.js canvas
var canvas = new fabric.Canvas();
// select all objects
function selectAllCanvasObjects(){
var objs = canvas.getObjects().map(function(o) {
return o.set('active', true);
});
var group = new fabric.Group(objs, {
originX: 'center',
originY: 'center'
});
canvas._activeObject = null;
canvas.setActiveGroup(group.setCoords()).renderAll();
}
I have a canvas and I need to select all text objects and skip others. 我有一个画布,我需要选择所有文本对象并跳过其他对象。 This is the code to select all objects, how can I make it only select all text objects and skip others?
这是选择所有对象的代码,如何使其仅选择所有文本对象而跳过其他对象?
The following example only selects items with the type
of 'text'
. 以下示例仅选择
'text'
type
的项目。
In summary: 综上所述:
The Fabric JS get
method allows us to inspect the type
of the current item that we're iterating over Fabric JS
get
方法允许我们检查要迭代的当前项目的type
If the type
is equal to 'text'
then we return the item 如果
type
等于'text'
则我们返回该项目
NB We now use filter
instead of map
, as we now only want to return items that match the type of 'text'
, instead of every item 注意:我们现在使用
filter
代替map
,因为我们现在只想返回与'text'
类型匹配的项目,而不是每个项目
var canvas = new fabric.Canvas('c'); // Add some example shapes var circle = new fabric.Circle({ radius: 20, fill: 'green', left: 100, top: 100 }); var triangle = new fabric.Triangle({ width: 20, height: 30, fill: 'blue', left: 50, top: 50 }); canvas.add(circle, triangle); // Add some example text var text1 = new fabric.Text('hello world', { left: 100, top: 100 }); var text2 = new fabric.Text('test', { left: 0, top: 0 }); canvas.add(text1, text2); // Select all objects function selectAllCanvasObjects(){ var objs = canvas.getObjects().filter(function(o) { if (o.get('type') === 'text') { return o.set('active', true); } }); var group = new fabric.Group(objs, { originX: 'center', originY: 'center' }); canvas._activeObject = null; canvas.setActiveGroup(group.setCoords()).renderAll(); } selectAllCanvasObjects();
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.8/fabric.min.js"></script> <canvas id="c"></canvas>
You can use below code to select all text object. 您可以使用以下代码选择所有文本对象。
var object_length = parseInt(canvas.getObjects().length) - 1;
for(var i = 0; i <= object_length; i++)
{
canvas.setActiveObject(canvas.item(i));
var obj = canvas.getActiveObject();
var object_type = obj.type;
if(object_type == "text")
{
//Write your code here
canvas.renderAll();
}
}
canvas.deactivateAllWithDispatch();
canvas.renderAll();
After completion of execution deselect all objects so it will not show you last selected object as selected. 执行完成后,请取消选择所有对象,这样就不会显示您上一次选择的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.