简体   繁体   English

Fabric.js:如何将自定义大小设置为 Text 或 IText?

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

I am using the excellent Fabric.js to draw some text in a canvas.我正在使用出色的 Fabric.js 在画布中绘制一些文本。 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.当我为 IText 对象指定自定义大小(假设为 200x200 矩形)时,似乎 Farbric.js 强制对象的宽度和高度适合文本。

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/这是我的问题的小提琴: http : //jsfiddle.net/K52jG/4/

In this example, I want the "Hello World!"在这个例子中,我想要“Hello World!” text to be in a 200x200 box.文本位于 200x200 框中。 Is it possible to do that, and how ?是否有可能做到这一点,以及如何做到这一点?

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好的,因为这是不可能的,所以我发现的最好方法是使用 Group 将 IText 框嵌套在 Rectangle 对象中

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/这个小提琴中的例子: 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该值似乎是:fontSize / 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM