FabricJs使用 -- 文本

3,630 阅读1分钟

Text

支持的操作

  1. Multiline support Native text methods unfortunately simply ignore new lines.
  2. Text alignment Left, center, right. Useful when working with multiline text.
  3. Text background Background also respects text alignment.
  4. Text decoration Underline, overline, strike-through.
  5. Line height Useful when working with multiline text.
  6. Char spacing Makes text more compact or more spaced
  7. Subranges apply colors and properties to subranges of your text object
  8. Multibyte support emoticons!
  9. On canvas editing with the interactive class you can type text directly over the canvas

举例

简单的初始化

 var text = new fabric.Text('hello world', { left: 100, top: 100 });
 canvas.add(text);

fontFamily

var comicSansText = new fabric.Text("I'm in Comic Sans", {
    fontFamily: 'Comic Sans'
});

设置字体

fontSize

var text40 = new fabric.Text("I'm at fontSize 40", {
    fontSize: 40
});

设置字体大小

fontWeight

var boldText = new fabric.Text("I'm at bold text", {
    fontWeight: 'bold'
});

textDecoration

 var underlineText = new fabric.Text("I'm an underlined text", {
    underline: true
});

shadow

 var shadowText1 = new fabric.Text("I'm a text with shadow", {
    shadow: 'rgba(0,0,0,0.3) 5px 5px 5px'
});

设置阴影

fontStyle

 var italicText = new fabric.Text("A very fancy italic text", {
    fontStyle: 'italic',
    fontFamily: 'Delicious'
});

stroke and strokeWidth

var textWithStroke = new fabric.Text("Text with a stroke", {
    stroke: '#ff1318',
    strokeWidth: 1
   });

textAlign

 var text = 'this is\na multiline\ntext\naligned right!';
    var alignedRightText = new fabric.Text(text, {
    textAlign: 'right'
    });

lineHeight

 var lineHeight3 = new fabric.Text('Lorem ipsum Lorem\nLorem ipsum Lorem\n', {
    lineHeight: 3
});

点击事件

var text = 'this is\na multiline\ntext\nwith\ncustom lineheight\n&background';
var textWithBackground = new fabric.Text(text, {
    textBackgroundColor: 'rgb(0,200,0)'
});
canvas.add(textWithBackground);
textWithBackground.on('selected', function() {
    console.log('selected');
});

参考

  1. 官网地址

联系我

关注微信号:大前端说,获取文章中提到的代码案例。库使用过程有什么问题,可以跟我沟通,加我的wx:meetbc。欢迎交流关于前端的任何话题。