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();
}
我有一个画布,我需要选择所有文本对象并跳过其他文本对象。这是选择所有对象的代码,如何才能使它只选择所有文本对象并跳过其他对象?
答案 0 :(得分:1)
以下示例仅选择type
'text'
的项目。
总结:
Fabric JS get
方法允许我们检查我们迭代的当前项目的type
如果type
等于'text'
,我们会退回商品
N.B。我们现在使用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>
答案 1 :(得分:0)
您可以使用以下代码选择所有文本对象。
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();
执行完成后,取消选择所有对象,使其不会显示您选择的最后一个选定对象。