8

How do I find the length of string in pixels in javascript , if I know the font-size and font-family?

KK123
  • 217
  • 1
  • 2
  • 10
  • and http://stackoverflow.com/questions/4910407/get-string-length-in-pixels-with-javascript?rq=1 and http://stackoverflow.com/questions/5353385/how-to-calculate-the-length-in-pixels-of-a-string-in-javascript?rq=1 – Dogbert May 10 '13 at 09:16
  • As there is here a better answer than in related questions, I now vote to reopen. – Denys Séguret May 11 '13 at 09:06
  • @dystroy I think it would make more sense to merge the answers from this question into the question's duplicate, so that all of the answers can be viewed on one page. – Anderson Green Aug 09 '13 at 19:38

2 Answers2

35

The simplest solution is to create an in memory canvas (i.e. one that isn't 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;
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • After having seen the links, I vote to close as duplicate but please note that my solution is different from the ones in the links (I didn't profile to compare). – Denys Séguret May 10 '13 at 09:21
  • 1
    this is nicer solution. The question was posted but the solutions given I found were using jQuery, whereas I do not have to use jQuery – KK123 May 11 '13 at 08:18
  • After having seen the other answers, I agree. I vote to reopen. You can accept this answer if it pleases you better. – Denys Séguret May 11 '13 at 09:02
  • IE8 and prior doest not support canvas, so any better solution? – hiway Nov 15 '13 at 02:22
  • 2
    You know Google doesn't support IE9 any more ? You might want to review the list of browsers you support. – Denys Séguret Nov 15 '13 at 06:23
1

you can put your string into paragraph and use the jquery width function to get the width in pixel width

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

check jsfiddle

Ganesh Bora
  • 1,133
  • 9
  • 17