sabah sabah -4 years ago 120
Javascript Question

How do I select ALL objects on canvas one by one with fabric js?

How would the code look like to select all objects currently on a canvas one by one using fabric js. I am trying to list the attributes of each object one by one without knowing how many objects (if any) will be on the canvas.

For clarification:

Here is a

var canvas = new fabric.Canvas('canvas');

canvas.add(new fabric.Text('hdgh', {
left: 20,
top: 30,
fontFamily: 'Comic Sans MS',
fontSize: 35

canvas.add(new fabric.Text('foo', {
fontFamily: 'Roboto',
left: 100,
top: 100,
fontSize: 25

canvas.add(new fabric.Text('f776h', {
fontFamily: 'Arial',
left: 200,
top: 200,
fontSize: 25

that has 3 objects... Is there a way I can print on the console log (text, fontFamily, and fontSize) of each text object)

1 object - 'hdgh' ; Comic Sans MS ; 35
2 object - 'foo' ; Roboto ; 25
3 object - 'f776h' ; Arial ; 25

Answer Source

Once you have a fabric objects, you can call fabric.getObjects() to get all of the objects. You can pass it a string, and that string can contain a type (like 'textbox' or 'circle') and it will only return the objects of that type.

Once you have the objects, you can loop over them as follows:

let objects = fabric.getObjects(); //return Array<objects>
    //list the attributes for each object
    console.log(object.text, object.fontFamily, object.fontSize);

Without a better description of what you are trying to do, this is what you can do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download