Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an object identifier in fabricjs?

Tags:

fabricjs

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()

like image 752
Faradey Avatar asked May 13 '15 18:05

Faradey


2 Answers

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.

like image 165
AndreaBogazzi Avatar answered Oct 06 '22 07:10

AndreaBogazzi


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();
like image 37
Theo Itzaris Avatar answered Oct 06 '22 06:10

Theo Itzaris