uddipana
uddipana

Reputation: 188

Assign object identifier to some objects in fabric.js and save it as json

I am using fabric.js to interact with canvas. I need to assign some objects unique id and then access those objects with the ids.

I got the following code from How to select Fabric.js object programmatically and added in fabric.js

  var object = {
     id:   this.id,
  } 

Now, I am adding the ids of some objects dynamically using the following codes:

for (i=0;i<10;i++)
{
  var rect = new fabric.Rect({
       left: 100,
       top: 100,
       fill: 'red',
        id: 'RECT'+i
       });
    alert(rect.id) //this is showing me the ids of each rectangle.
}

But the situation is I need to save these ids in json, so that once when I load the json I can access the objects through program by their ids. I tried following code:

  var json = JSON.stringify( canvas.toDataLessJSON(['id']) );

With this I am not getting the ids in the JSON. Please suggest me a way by which I can save ids of few objects into JSON.

Upvotes: 3

Views: 3490

Answers (1)

Tim Harker
Tim Harker

Reputation: 2417

Here's a working JSFiddle: http://jsfiddle.net/rekrah/dw3bakkp/

Try this: var json = JSON.stringify(canvas.toJSON(['id']));

And to load the canvas from JSON and access the objects by their ids:

var rectOne, rectTwo;  
canvas.loadFromJSON(json, function () {}, 
  function (o, object) {
    switch (object.id) {
        case 'RECT1':
            rectOne = object;
            break;            
        case 'RECT2':
            rectTwo = object;
            break;
        default:
            break;
    }
});

And here's a website I'm putting together that uses the code:

http://xpressclocks.azurewebsites.net/customize/abstract/liquid/white-paint-splash-on-black-background

Upvotes: 4

Related Questions