如何设置我绘制的fabricjs文本对象的部分样式?

时间:2017-12-11 15:43:00

标签: javascript html css fabricjs

我有一些代码可以让我在文本对象之间切换。我希望文本对象包含一些样式,如Bold,Italic等,用于标题等。但是,我不确定如何实现这一目标。这是我目前的代码:



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用styles属性设置单个字符的样式

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

&#13;
&#13;
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}
     }
     }
   }));
 }
&#13;
canvas {
  border: 1px solid #dddddd;
  border-radius: 3px;
  margin-top: 5px;
}
&#13;
<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>
&#13;
&#13;
&#13;