I need to calculate my text with using JavaScript. But can't find a simple and working method. Please, help me :) Thanks in advance.
Asked
Active
Viewed 3,054 times
0
-
Are we referring to DOM, or Canvas? – Mr. Polywhirl Jul 02 '20 at 11:26
1 Answers
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