Measuring string length in pixels in javascript

How to find the length of a string in pixels in javascript if I know the font size and font family?

+4
source share
2 answers

The simplest solution is to create a canvas in memory (i.e. one that is not added to the DOM), and then use the measureText function:

 var canvas = document.createElement('canvas'); var ctx = canvas.getContext("2d"); ctx.font = "11px Arial"; var width = ctx.measureText(str).width; 
+25
source

you can put your line in a paragraph and use the jquery width function to get the width in pixels width

  function showWidth(ele, w) { $("div").text("The width for the " + ele + " is " + w + "px."); } $("#getp").click(function () { showWidth("paragraph", $("p").width()); }); 

check jsfiddle

+1
source

Source: https://habr.com/ru/post/1480079/


All Articles