How to scale a Text object to a given height using FabricJS?


In this tutorial, we are going to learn how to scale a Text object to a given height using FabricJS. We can display text on canvas by adding an instance of fabric.Text. Not only does it allow us to move, scale and change the dimensions of the text but it also provides additional functionality like text alignment, text decoration, line height which can be obtained by the properties textAlign, underline and lineHeight respectively. Similarly we can also scale a Text object to a given height by using the scaleToHeight method.

Syntax

scaleToHeight(value: Number, absolute: Boolean)

Parameters

  • value − This parameter accepts a Number which determines the new height value of our text object.

  • absolute − This parameter accepts a Boolean value which determines whether the viewport is to be ignored or not.

Example 1

Default appearance of the Text object

Let’s see a code example to see how our text object looks when the scaleToHeight method is not used. In this case, our text object will not be scaled in horizontal or vertical directions.

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Default appearance of the Text object</h2> <p>You can see that the object has not been scaled in horizontal or vertical direction</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Add sample
text here."
, { width: 300, left: 60, top: 70, fill: "green", }); // Add it to the canvas canvas.add(text); </script> </body> </html>

Example 2

Passing the scaleToHeight method with a custom value

In this example we will see how assigning a value to the scaleToHeight method scales our text object to a given height. Since we have passed the value as 300, that will be the new height of our text object.

<!DOCTYPE html> <html> <head> <!-- Adding the Fabric JS Library--> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script> </head> <body> <h2>Passing the scaleToHeight method with a custom value</h2> <p>You can see that the new height of our text object is 300</p> <canvas id="canvas"></canvas> <script> // Initiate a canvas instance var canvas = new fabric.Canvas("canvas"); canvas.setWidth(document.body.scrollWidth); canvas.setHeight(250); // Initiate a text object var text = new fabric.Text("Add Sample
Text Here."
, { width: 300, left: 60, top: 70, fill: "green", }); // Using scaleToHeight method text.scaleToHeight(300, false); // Add it to the canvas canvas.add(text); </script> </body> </html>

Updated on: 14-Sep-2022

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements