Categories
JavaScript Answers

How to Calculate Text Width with JavaScript?

Spread the love

Sometimes, we’ve to calculate the width of text content in our JavaScript code.

In this article, we’ll look at how to calculate text content width in our JavaScript code.

clientHeight and clientWidth

The clientHeight and clientWidth properties of an HTML element object lets us get the height and width of the element.

Therefore, we can write the following HTML:

<p id='text'>  
  hello world  
</p>

to create the element.

Then we can write the JavaScript coder to get the height and width of the element:

const fontSize = 12;  
const text = document.getElementById("text");  
text.style.fontSize = fontSize;  
const height = text.clientHeight  
const width = text.clientWidth  
console.log(height, width);

We get the p element with getElementById .

Then we use the clientHeight and clientWidth propetties to get the height and width of the p element respectively.

Then we log that with the console.

We should get something like:

18 222

from the console log.

The numbers are in pixels.

Canvas.measureText Method

The HTML canvas element has the measureText method that lets us measure the size of a piece of text.

This means that we can put our text into the canvas and then call that to measure its size.

For instance, we can write:

const text = 'hello world'  
const font = "bold 12pt arial"  
const canvas = document.createElement("canvas");  
const context = canvas.getContext("2d");  
context.font = font;  
const {  
  width  
} = context.measureText(text);  
console.log(width)

We have the text and font variables with the text content and font styles respectively.

Then we create a canvas with createElement .

And we call getContext to get the context.

Next, we set the font property with the font styles.

And then we call measureText with the text variable to measure the size of text .

We get the width property from the returned object.

And we should see a number like 84.4453125 logged from the console log.

The number is also in pixels.

Conclusion

We can either measure text size with the clientHeight and clientWidth properties of an element.

Also, we can put our text into the canvas and use the measureText method to measure the text width.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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