Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...