Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the length (in pixels) of a string in JavaScript?

Tags:

javascript

How to calculate the length (in pixels) of a string in JavaScript?

like image 305
isxaker Avatar asked Mar 18 '11 14:03

isxaker


2 Answers

you can use simple code

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";        
var width = ctx.measureText(str).width;
like image 113
Behnam Mohammadi Avatar answered Oct 12 '22 22:10

Behnam Mohammadi


Given the new information about your wanting to append an ellipsis for text overflow, I think the text-overflow CSS property is a better approach. See this article on quirksmode for more information: http://www.quirksmode.org/css/textoverflow.html

like image 43
Zikes Avatar answered Oct 13 '22 00:10

Zikes