Search code examples
javascriptfabricjs

Manually set bounding box for text object in fabricjs canvas


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.


Solution

  • 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>