Fabric.js : How to set a custom size to Text or IText?

不想你离开。 提交于 2019-12-09 13:19:14

问题


I am using the excellent Fabric.js to draw some text in a canvas. When I specify a custom size ( let's say a 200x200 rectangle) to my IText Object, it seems that Farbric.js force the width and the height of the object to fit around the text.

var t = new fabric.IText("Hello world !", {
  top: 100,
  left: 100,
  width: 200,
  height:200,
  backgroundColor: '#FFFFFF',
  fill: '#000000',
  fontSize: 12,
  lockScalingX: true,
  lockScalingY: true,
  hasRotatingPoint: false,
  transparentCorners: false,
  cornerSize: 7
});

Here is a Fiddle with my problem : http://jsfiddle.net/K52jG/4/

In this example, I want the "Hello World!" text to be in a 200x200 box. Is it possible to do that, and how ?


回答1:


OK, so because it is not possible, the best way I found to is to nest the IText box in a Rectangle object, using a Group

var r = new fabric.Rect({
    width: 200, 
    height: 200, 
    fill: '#FFFFFF',
  });


// create a rectangle object
var t = new fabric.IText("Hello world !", {
  backgroundColor: '#FFFFFF',
  fill: '#000000',
  fontSize: 12,
  top : 3,


});


var group = new fabric.Group([ r, t ], {
  left: 100,
  top: 100,
  lockScalingX: true,
  lockScalingY: true,
  hasRotatingPoint: false,
  transparentCorners: false,
  cornerSize: 7


});

Example in this Fiddle : http://jsfiddle.net/4HE3U/1/

Note : I have to set a "top" value to the text because it goes out of the box. The value seem to be : fontSize / 4



来源:https://stackoverflow.com/questions/21187154/fabric-js-how-to-set-a-custom-size-to-text-or-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!