How to Calculate Text Width with JavaScript

There are DOM methods that are used to calculate the text width; however in this tutorial, you will find the best method to do the task accordingly. You can use the Canvas.measureText() method in JavaScript to detect the text width accurately. Note that the font here is a string, and actually a CSS font value should be passed to the function (in this example we have used italic 19pt verdana).

Javascript calculate text width
function displayTextWidth(text, font) { let canvas = displayTextWidth.canvas || (displayTextWidth.canvas = document.createElement("canvas")); let context = canvas.getContext("2d"); context.font = font; let metrics = context.measureText(text); return metrics.width; } console.log("Text Width: " + displayTextWidth("This is demo text!", "italic 19pt verdana")); //

The measureText() Method

The measureText() method returns an object which represents the width of the given text in terms of pixels. It can be used to detect the text width before writing it on canvas.

This approach has some advantages:

  • It is more concise and safer than the other DOM-based methods as it does not change the global state.
  • Further customization is possible by modifying more canvas text properties, such as textAlign and textBaseline.

Adding the text to your DOM, take into account the padding, margin and border.

This method provides sub-pixel accuracy, i.e. the result is a floating-point number on some browsers; on others it does not. In such cases, you should run Math.floor (or Math.ceil) on the result to avoid inconsistencies. The Canvas.measureText() method is the fastest compared to the other methods.