Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS: Vertical Align text center

I am using fabricjs 1.5 and I am stuck on aligning the text in the middle of the line vertically. I am using this code to set the line height

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

It changes the line height of text on canvas but text always remains at the top. I want it to be in the vertically middle. Please help.

like image 895
Ashish Avatar asked Oct 28 '25 19:10

Ashish


2 Answers

  • set text origin to 'center'
  • set text position to box center
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

like image 59
Mila Nautikus Avatar answered Oct 30 '25 10:10

Mila Nautikus


You need to use newer versions of fabricjs. 1.5 is too old. For alignment use fabric.Textbox textAlign property.

DEMO

var canvas = new fabric.Canvas("canvas");
canvas.add(new fabric.Textbox('FabricJS is Awsome',{width:300,textAlign:'center'}));
canvas{
 border: 1px solid #000;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fabric.min.js"></script>
<canvas id="canvas" width=400 height=400></canvas>
like image 43
Durga Avatar answered Oct 30 '25 08:10

Durga