Can we change color of selected text in fabricjs?

Viewed 43

does any body know how to change color of selected text in fabricjs?

my code is

canvas.getActiveObject().set("fontFamily", this.value);

But this code is changing color of whole text block

1 Answers

You can update individual characters by using the style property.

http://fabricjs.com/docs/fabric.Text.html#styles

const canvas = new fabric.Canvas('canvas');
canvas.setWidth(document.body.clientWidth);
canvas.setHeight(document.body.clientHeight);

const text = new fabric.Text('some text', {
  fill: 'green',
  styles: {
    0: {
      0: {
        fill: 'red',
      },
      1: {
        fill: 'blue'
      }
    }
  }
});

canvas.add(text);
body,
html {
  width: 100%;
  height: 100%;
}
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/521/fabric.min.js" integrity="sha512-nPzvcIhv7AtvjpNcnbr86eT6zGtiudLiLyVssCWLmvQHgR95VvkLX8mMpqNKWs1TG3Hnf+tvHpnGmpPS3yJIgw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related