Alex Kerr
Alex Kerr

Reputation: 1080

Easily convert between Fabric JS IText and Textbox?

Is there a way to easily convert a Fabric JS IText into a TextBox (new in 1.6.0) and vice versa, without having to laboriously read and set every single property of them, i.e. some quick way of mapping between them?

Thanks.

Upvotes: 0

Views: 2255

Answers (1)

AndreaBogazzi
AndreaBogazzi

Reputation: 14731

you can easily do

var text = oldItext.text;
var textobj = oldItext.toObject();
delete textobj.text;
delete textobj.type;
var clonedtextobj = JSON.parse(JSON.stringify(textobj));

var textbox = new fabric.Textbox(text, clonedtextobj);

a note about use of json:

normal toObject method in Fabricjs does not take care of deep cloning. so the new textbox you create would share the same style object with the old itext. That is not necessarly bad untill you create 2 copies from 1.

if you are not using styles, a faster way is:

var text = oldItext.text;
    var textobj = oldItext.toObject();
    delete textobj.type;
    var textbox = new fabric.Textbox(text, textobj);

Upvotes: 3

Related Questions