How do I find the length of string in pixels in javascript , if I know the font-size and font-family?
-
and stackoverflow.com/questions/4910407/… and stackoverflow.com/questions/5353385/…Dogbert– Dogbert2013-05-10 09:16:35 +00:00Commented May 10, 2013 at 9:16
-
As there is here a better answer than in related questions, I now vote to reopen.Denys Séguret– Denys Séguret2013-05-11 09:06:18 +00:00Commented 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.Anderson Green– Anderson Green2013-08-09 19:38:26 +00:00Commented Aug 9, 2013 at 19:38
Add a comment
|
2 Answers
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;
5 Comments
Denys Séguret
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).
KK123
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
Denys Séguret
After having seen the other answers, I agree. I vote to reopen. You can accept this answer if it pleases you better.
hiway
IE8 and prior doest not support canvas, so any better solution?
Denys Séguret
You know Google doesn't support IE9 any more ? You might want to review the list of browsers you support.
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());
});