8

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

3
  • and stackoverflow.com/questions/4910407/… and stackoverflow.com/questions/5353385/… Commented May 10, 2013 at 9:16
  • As there is here a better answer than in related questions, I now vote to reopen. Commented May 11, 2013 at 9: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. Commented Aug 9, 2013 at 19:38

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

5 Comments

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).
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
After having seen the other answers, I agree. I vote to reopen. You can accept this answer if it pleases you better.
IE8 and prior doest not support canvas, so any better solution?
You know Google doesn't support IE9 any more ? You might want to review the list of browsers you support.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.