Search code examples
htmltypescriptcanvasfabricjs

Change IText color in Fabric.JS canvas (using React + typescript)


I have input with type=color outside Canvas. I have canvas with one ore more IText objects (as well as other objects). What I wanted to achieve is "on input change, change color of select text objects".

This is my input within React

<input type="color" defaultValue={defaultTextColor} ref={myRef} onChange={handleColorChange} />

I am able to change "text", but not color...

This is my Color Change event

const handleColorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newColor = e.currentTarget.value;
    canvas.getActiveObjects().forEach((element: any) => {
      if(element.type == 'i-text') {
          element.color = newColor; //this doesn't work
          element.text = "new"; // this works
      }
    });
    
    canvas.renderAll();
  }

Solution

  • Firstly, the color of a text is defined in the property fill

    Then you need to use the set and renderAll functions.

    Here is an example

            var canvas = new fabric.Canvas("canvas");
            var myText = new fabric.Text("Hello", {
                top: 100,
                left: 100,
                width: 60,
                height: 70,
                fill: "red",
            });
            setTimeout(() => {
                myText.set("fill", "green");
                canvas.renderAll();
            }, 2000);
    
            canvas.add(myText);