Reputation: 188
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
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:
Upvotes: 4