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

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

+4
source share
4 answers

Given the new information that you want to add an ellipsis for text overflow, I think the CSS overflow property is the best approach. See this quirksmode article for more information: http://www.quirksmode.org/css/textoverflow.html

+3
source

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; 
+2
source

A working simshaun suggestion example: http://jsfiddle.net/tycjf/2/

+1
source

The easiest way is to write it to a range on the page, get the width, and then delete the range. Also, this is relative to any font size that inherits a range.

0
source

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


All Articles