Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style part of my drawn fabricjs text object?

I have some code that allows me to toggle between text objects. I'd like to have the text objects include some styling, like Bold, Italic, etc for titles and such. text, however, am not sure how to accomplish this. Here's my current code:

var canvas = this.__canvas = new fabric.Canvas('c');
 canvas.setHeight(300);
 canvas.setWidth(500);
  
 function textOne() {
   canvas.clear();
   canvas.add(new fabric.IText('Regular Font', {
     left: 50,
     top: 100,
     fontFamily: 'arial',
     fill: '#333',
     fontSize: 50
   }));
 }
 
  function textTwo() {
   canvas.clear();
   canvas.add(new fabric.IText('Bold Font', {
     left: 50,
     top: 100,
     fontFamily: 'arial',
     fontWeight: 'bold',
     fill: '#333',
     fontSize: 50
   }));
 }
canvas {
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-top: 5px;
}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button onclick="textOne()">One</button>
<button onclick="textTwo()">Two</button>
<canvas id="c"></canvas>
like image 251
anonymoose Avatar asked Oct 23 '25 15:10

anonymoose


2 Answers

You can use the styles property to style individual characters

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

var canvas = this.__canvas = new fabric.Canvas('c');
 canvas.setHeight(300);
 canvas.setWidth(500);
  
 function textOne() {
   canvas.clear();
   canvas.add(new fabric.IText('Regular Font', {
     left: 50,
     top: 100,
     fontFamily: 'arial',
     fill: '#333',
     fontSize: 50,
     styles:{
     0:{
      0:{fontWeight: 'bold'},
      1:{fontWeight: 'bold'}
     }
     }
   }));
 }
 
  function textTwo() {
   canvas.clear();
   canvas.add(new fabric.IText('Bold Font', {
     left: 50,
     top: 100,
     fontFamily: 'arial',
     fontWeight: 'bold',
     fill: '#333',
     fontSize: 50,
     styles:{
     0:{
      0:{fontSize: 40},
      1:{fontSize: 30}
     }
     }
   }));
 }
canvas {
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-top: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.min.js"></script>
<button onclick="textOne()">One</button>
<button onclick="textTwo()">Two</button>
<canvas id="c"></canvas>
like image 171
user700284 Avatar answered Oct 26 '25 04:10

user700284


If you want to also update the styles dynamically, you can use setSelectionStyles method like this:

const text = new fabric.TextBox('Regular Font', {
  left: 50,
  top: 100,
  fontFamily: 'arial',
  fill: '#333',
  fontSize: 50,
});
const start = 0
const end = 5
text.setSelectionStyles({fontWeight: 'bold'}, start, end);
like image 32
stanko Avatar answered Oct 26 '25 04:10

stanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!