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.

1
  • Are we referring to DOM, or Canvas? Commented Jul 2, 2020 at 11:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.