Even Better Multiline Text Boundary Fitting For Fabric.js Text Objects

This is a revision of my previous post detailing how to get Fabric.js text objects with multiline strings to fit within a preset viewport or boundary. The original post can be found here. This version has been revised and will now automatically scale the font size to copyfit the text when the height of the text object is larger of the preset dimensions. In the previous version it would stop displaying the new lines.

This object will need to be customized to your specific needs. I may consider turning it into a library once it has been further tested. Here is an example of how to use it:

Provide the formatter object with the width and height of the viewport boundary. The formatter will then make sure that your text fits within that viewports boundary.

3 thoughts on “Even Better Multiline Text Boundary Fitting For Fabric.js Text Objects”

  1. I am running into all sorts of errors.

    First I get an error on line 8 this.textLayer.options.font_size_default <- where are the options set?

    When I look at the source I am not sure where the canvasEle property on this.textLayer is coming from. Fabric.js doesn't seem to have a property canvasEle. I don't know of DesignerWorkspace either.

    Maybe I just don't understand what I am passing in as "textLayer". It doesn't appear to be run of the mill fabric.Text.

    Any help would be great. thanks.

    1. Hey LeRoy,

      Yea, I should clean this up a bit. Let me see if I can just describe what you need to do based on your questions and then maybe one day this weekend I’ll go through this a really create a reusable script.

      For the font question, you’ll need to find a way to set that based on your app. While you’re testing just replace this.textLayer.options.font_size_default with any number you want to start with as the default font size.

      canvasEle is the Fabric.Text object that you added to the FabricJS canvas and want to use the script to fit. So replace self.textLayer.canvasEle with the Fabric.Text object that you created and added to the Fabric.canvas.

      self.textLayer.designerWorkspace.canvas is the Fabric.canvas element. So replace that variable with your variable that you are using to reference the canvas.

      Thanks,

      Kevin Allen Rio

      1. Thanks for the reply. I was really concerned that there was just something I wasn’t setting up correctly. Knowing what the parts actually are, I was able to get it up and functioning.

        I really appreciate your sharing this script. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *