Calculate text width with JavaScript.

JavascriptObject Oriented ProgrammingFront End Technology

To calculate text width, use the Canvas.measureText() method in JavaScript. You can try to run the following code to get the text width −


<!DOCTYPE html>
         function displayTextWidth(text, font) {
            var myCanvas = displayTextWidth.canvas || (displayTextWidth.canvas = document.createElement("canvas"));
            var context = myCanvas.getContext("2d");
            context.font = font;
            var metrics = context.measureText(text);
            return metrics.width;
         document.write("Text Width: "+displayTextWidth("This is demo text!", "italic 18pt verdana")); //
Updated on 23-Jun-2020 11:44:16