简体   繁体   中英

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

I am using Fabric.js to create a drawing canvas. 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.

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? 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/

You can accessing individual objects in a group via item() method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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