Categories
JavaScript Answers

How to measure text width and height without rendering with JavaScript?

Spread the love

Sometimes, we want to measure text width and height without rendering with JavaScript.

In this article, we’ll look at how to measure text width and height without rendering with JavaScript.

How to measure text width and height without rendering with JavaScript?

To measure text width and height without rendering with JavaScript, we can put the text in a canvas element and measure it there.

For instance, we write:

const getTextSize = (txt, font) => {
  const element = document.createElement('canvas');
  const context = element.getContext("2d");
  context.font = font;
  const tSize = {
    'width': context.measureText(txt).width,
    'height': parseInt(context.font)
  };
  return tSize;
}

const tSize = getTextSize("Hello World", "30px Arial");
console.log(tSize)

to define the getTextSize function that takes the txt text and font.

In it, we create the canvas element with document.createElement.

Then we call element.getContext to get the context.

Next, we set the font of the context.

And then we do the measure with the context.measureText method.

And we get the font height with context.font.

As a result, tSize should be {width: 154.4970703125, height: 30} according to the console log.

Conclusion

To measure text width and height without rendering with JavaScript, we can put the text in a canvas element and measure it there.

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 *