Jack M.
Jack M.

Reputation: 1170

FabricJS text color is object

I am trying to load the text color in a color picker. However, when I do get("fill") on the activeobject I loaded from JSON, it gives me an object. Here is the offending JSON line:

"fill":{"ok":true,"format":"hex6","_tc_id":258,"alpha":1}

How am I supposed to turn that into a color and not an object Object?

Adding jsfiddle:

http://jsfiddle.net/Qb4Xe/5/

Just click on the text!

Upvotes: 4

Views: 4568

Answers (1)

Franco Rondini
Franco Rondini

Reputation: 11001

You are right, the problem is that you are restoring the canvans by loading a json that contains a wrong value for the fill property, explicitly:

 "fill":{"ok":true,"format":"hex6","_tc_id":258,"alpha":1}

probably this object is coming from the serialization of a TinyColor

Unfortunately this can not be interpreted correctly by fabricjs and can not be converted back into a hex color (see the sources of TinyColor if you need to delve this point )

I create this fiddle to shows how it is possible to reproduce a similar mistake; suppose we have a TinyColor

var t = tinycolor("#ff0000");

We make a mistake if we use this TinyColor object as the value of the fill property ( i.e. fill: t ), for example:

canvas.add(new fabric.Rect({ width: 50, height: 50, fill: t, top: 100, left: 100 }));

by serializing the canvas we get a JSON that contains:

"fill":{"ok":true,"format":"hex","_tc_id":0,"alpha":1},

but this can not work and the actual fill is visualized as black ( the default ) instead of our color ( red ).

The correct approach is to use fill: t.toHexString():

canvas.add(new fabric.Rect({ width: 50, height: 50, fill: t.toHexString(),  top: 150, left: 150 }))

this works fine ( the rectangle is red ) moreover by serializing the canvas we get a JSON that contains:

"fill":"#ff0000"

therefore this will work fine even when you will restore the canvans from JSON.

EDIT

Ultimately suggest is to fix the problem at the origini, but if you have to deal with a buggy json string also is possible to intercept the problem this way:

if (typeof hex == "object" && hex.hasOwnProperty("_tc_id")) {
   alert("no color available; return a default such as fill:'none'");
}

like in this fork the fiddle post in the question

Upvotes: 6

Related Questions