简体   繁体   English

Fabric.js:如何获取组中对象的属性值?

[英]Fabric.js: How to get the properties' value of the object in a group?

I am using Fabric.js to create a drawing canvas. 我正在使用Fabric.js来创建绘图画布。 May I know is there anyway to get the properties' value of the objects in a group object? 我是否知道有没有获得组对象中属性的属性值?

For example: I created a rectangle and a text object, and grouped them together 例如:我创建了一个矩形和一个文本对象,并将它们组合在一起

new fabric.group([rect1,text1],{
        top:100,
        left:100
    });

I have tried like below: 我尝试过如下:

var objsInCanvas = canvas.getObjects();
for (obj in objsInCanvas) {
    return objsInCanvas[obj].get('text')
}

But it doesn't get the value of the text for me. 但它并没有为我获得文本的价值。 Can someone please give a advice on this? 有人可以就此提出建议吗?

I don't have enough rep to comment yet, but I can see a couple of things that might be causing this. 我还没有足够的回复评论,但我可以看到一些可能导致这种情况的事情。 Without more code, I'm going to have to assume a couple of things. 没有更多的代码,我将不得不承担一些事情。

First off, when instantiating a new group, you need to capitalize the Fabric object. 首先,在实例化新组时,需要将Fabric对象大写。

var group = new fabric.Group([rect1, text1],{
  ...    
});

Second, if you haven't, you need to add your group to the canvas 其次,如果还没有,则需要将您的组添加到画布

canvas.add(group);

I'm sure you did that in your code, but eh. 我确定你在代码中做到了,但是呃。 Then we can get to the good stuff... 然后我们可以找到好东西......

Your for loop grabs all of the objects on the canvas, right? 你的for循环抓住了画布上的所有对象,对吧? It turns out if your object is in a group, then you are grabbing that group itself, and not the individual objects within. 事实证明,如果您的对象在一个组中,那么您将抓取该组本身,而不是其中的单个对象。 You need to iterate through all the objects in that group as well to get any properties from them. 您还需要迭代该组中的所有对象以从中获取任何属性。

I made a quick fiddle just to see if I could get it working. 我做了一个快速的小提琴只是为了看看我是否能让它运转起来。 It should give you an idea of what you need to do. 它应该让你知道你需要做什么。

http://jsfiddle.net/pUw5k/ http://jsfiddle.net/pUw5k/

You can accessing individual objects in a group via item() method: 您可以通过item()方法访问组中的单个对象:

For Example: 例如:

group.item(0).set({
  text: 'trololo',
  fill: 'white'
});  //Retrieve item(0) and sets its properties

group.item(1).setFill('red'); ////Retrieve item(1) and sets its properties

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

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