Reputation: 371
How to get an object identifier in fabricjs? For example
var text = new fabric.IText('hello world', { left: mouse1X, top: mouse1Y });
ID = text.get???
This identifier should be present in
JSON.stringify(canvas)
canvas.loadFromJSON()
identifier should be present in the JSON.stringify(canvas)
canvas.loadFromJSON()
Upvotes: 13
Views: 19783
Reputation: 14731
When you create an object, pass along the options an id
attribute:
var obj = fabric.Object({id: 'myid'});
or add at runtime:
obj.id = 'myid';
When saving to JSON use the propertiesToInclude
parameter to specify you want to save it:
obj.toJSON(['myid', 'others...']);
or
canvas.toJSON(['myid', 'others...']);
Loading back will be automatic.
Upvotes: 25
Reputation: 4681
There are not id attributes on the objects, but you can create your own. like this:
var msg = 'hello world';
var myId = 1;
var text = new fabric.IText(msg, {
left: mouse1X,
top: mouse1Y,
id: myId //my custom property
});
canvas.add(text);
//get id value
console.log(text.get('id'));
//OR
console.log(text.id));
//change id value
text.set('id',5);
//OR
text.id = 5;
canvas.renderAll();
Upvotes: 3
Reputation: 3
Add an id when creating any object like this:
// functions that generates an id
function generateId(type) {
return `${type}-${Math.random().toString(36).substr(2, 9)}`;
}
const rectangle = new fabric.Rect({
id: generateId('rect'),
left: 150,
top: 45,
});
So, you can reset ids by passing the reviver callback to loadFromJSON
.
// function to be passed as reviver callback
function resetObjectsIds(o, object) {
object.set({ id: generateId(object.get('type')) });
}
// when loading json...
canvas.loadFromJSON(
canvasJson,
canvas.renderAll.bind(canvas),
resetObjectsIds, // here is the reviver callback function
);
Now, every time you save or load the canvas, it will have ids.
Upvotes: 0