0

When I add a text object to my canvas using fabricJs, the bounding box is automatically calculated based on the size of the text rendered. Is there a way to manually set the coordinates of the bounding box?

For example, I can place text using the following

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

But the bounding box is calculated automatically. What if I wanted a very wide box with right-aligned text? I'd like to do something like this:

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

But the width appears to be ignored and the text appears aligned at the (100,100) position instead of to the right.

C_Z_
  • 7,427
  • 5
  • 44
  • 81

1 Answers1

1

If I understand you correctly, then you can try using TextBox with the editable: false parameter instead of Text. Example below:

const canvas = new fabric.Canvas('demo');

const textBox = new fabric.Textbox('Popular greeting:\n "Hello World"', {
  width: 250,
  top: 50,
  left: 50,
  fontSize: 22,
  textAlign: 'right',
  fixedWidth: 250,
  padding: 2,
  editable: false
});

canvas.add(textBox);
#demo {
  background-color: grey;
  margin-top: 10px;
  border: 1px solid #000000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
<canvas id="demo" width="400" height="400"></canvas>
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17
  • Thanks, this is great. For whatever reason, `editable: false` doesn't seem to be preventing moving the textbox around, which is what I would expect. But I'll figure it out, thanks! – C_Z_ Aug 11 '22 at 15:29
  • @C_Z_, To prevent moving (rotating, scaling, ...) the field, you can pay attention to the "lock" properties, for example [`lockMovementX`](http://fabricjs.com/docs/fabric.Textbox.html#lockMovementX), [`lockMovementY`](http://fabricjs.com/docs/fabric.Textbox.html#lockMovementY), [`lockRotation`](http://fabricjs.com/docs/fabric.Textbox.html#lockRotation), etc. - there are many similar properties in the [TextBox documentation](http://fabricjs.com/docs/fabric.Textbox.html) – Oleg Barabanov Aug 11 '22 at 15:43
  • Thanks! One more question if you happen to know the answer... is there a way to vertically align text within a textbox? The docs mention the `textAlign` property which does horizontal alignment, but I wonder if there's an easy way to do vertical alignment? – C_Z_ Aug 11 '22 at 15:51
  • 1
    @C_Z_, Vertical alignment unfortunately is not so simple there. Perhaps this solution can help you: https://stackoverflow.com/a/59269666/17182878 – Oleg Barabanov Aug 11 '22 at 16:21