0

I need to calculate my text with using JavaScript. But can't find a simple and working method. Please, help me :) Thanks in advance.

Siranush
  • 1
  • 1
  • 10

1 Answers1

2

Hi :) Recently I have found a really simple and handy method. Just use the Canvas.measureText() method in JavaScript to detect the text width properly:

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 code and info is taken from this tutorial of W3docs.

Nancy Brown
  • 360
  • 3
  • 2