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 −

Example

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <script>
         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")); //
      </script>
   </body>
</html>
raja
Published on 27-Feb-2018 15:06:36
Advertisements