Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

html - 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();
  }
question from:https://stackoverflow.com/questions/65927338/change-itext-color-in-fabric-js-canvas-using-react-typescript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...