FabricJS:垂直对齐文本中心

时间:2018-06-02 11:49:35

标签: javascript canvas fabricjs

我正在使用fabricjs 1.5而且我不得不垂直对齐文本在行的中间。 我正在使用此代码来设置行高

text.setProperty('lineHeight', $scope.lineHeight.current);

它会更改画布上文本的行高,但文本始终保持在顶部。我希望它在垂直中间。请帮忙。

2 个答案:

答案 0 :(得分:0)

您需要使用更新版本的fabricjs。 1.5太旧了。对齐使用fabric.Textbox textAlign属性。

<强> 样本

&#13;
&#13;
var canvas = new fabric.Canvas("canvas");
canvas.add(new fabric.Textbox('FabricJS is Awsome',{width:300,textAlign:'center'}));
&#13;
canvas{
 border: 1px solid #000;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="canvas" width=400 height=400></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

  • 将文本原点设置为“居中”
  • 将文本位置设置为框中心
const box_width = 100
const box_height = 100

// box
var rect = new fabric.Rect({
    width: box_width, height: box_height,
    fill: false, stroke: '#000',
})

// text
// vertical align = center
var text = new fabric.Text(
    'hello', {
    originX: 'center', originY: 'center',
    left: 0.5*box_width, top: 0.5*box_height,
})

// group
var group = new fabric.Group(
    [rect, text], {
    left: 50, top: 50,
})

canvas.add(group)

fiddle

相关问题