SoFunction
Updated on 2025-03-01

How to calculate the width of a string text in JavaScript

JS calculates the width of string text

When using canvas to make animations, you often need to get the width of the string and the edges to compare. The following is a way to get the width of any string through js:

function getTextWidth(text, fontSize) {
	// Create temporary elements	const _span = ('span')
	// Put in text	_span.innerText = text
	// Set text size	_span. = fontSize + 'px'
	// Span element to block level	_span. = 'absolute'
	// Put the span into the body	(_span)
	// Get the width of the span	let width = _span.offsetWidth
	// Remove the span from the body	(_span)
	// Return to span width	return width
}

JS calculates arbitrary string width

PS: It's width, not length!

Due to limitations such as pixel and font size, bytes (especially UTF-8), we cannot directly know the actual width occupied by a string.

Here are several comparison measurement methods:

1. Measured by Canvas

/**
 * Uses  to compute and return the width of the given text of given font in pixels.
 * 
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (. "bold 14px verdana").
 * 
 * @see /questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, font) {
  // re-use canvas object for better performance
  var canvas =  || ( = ("canvas"));
  var context = ("2d"); 
   = font;
  var metrics = (text);
  return ;
}
 
(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86

2. Measure through DOM

When this method contains multiple spaces in a string, the measured width will be the same.

For example: ''Tmall flagship store     49.67%(tmall)'' and ''Tmall flagship store                                                                                                                                               �

function getTextWidth(str = '') {
  const dom = ('span');
   = 'inline-block';
   = 'Tmall flagship store   49.67%(tmall)';
  (dom);
  const width = ;
  ();
  (dom);
  return width;
}

3. Use visibility: hidden

The floating layer to calculate the string width.

Set the style to the same as your actual div in the added div container.

<!DOCTYPE html>
<html> 
<head>
  <script src=''></script>
</head>
<body>
  <div
    id='labelText' 
    style='color:black; line-height:1.2; white-space: nowrap; position:fixed;
      top:0px; left:0px; display:block; visibility:visible;'
  ></div>
 
  <script>
    var str = 'Live like you were dying, Love because you do.';
    str = (0, );
    $('#labelText').css({
      'font-size': '12px',
      'font-family': 'Microsoft YaHei'
    }).html(str);
    var width = $('#labelText').width();
    (width);
  </script>
</body>
</html>

The same is true for the calculation height.

Finally don't forget to remove the extra div!

Code:

let tCanvas = null;
getTextWidth(text, font = 'normal 12px sans-serif') {
  // re-use canvas object for better performance
  const canvas = tCanvas || (tCanvas = ('canvas'));
  const context = ('2d');
   = font;
  return (text).width;
}
 
addStrWidthViaBlank(str, width) {
  // This function is only applicable to strings in the form of 'xxx xx' (that is, the original string contains spaces)  if (width &lt;= 0 || ((str) &gt;= width)) {
    return str;
  }
 
  let tStr = str;
  let tWidth = 0;
  while (tWidth &lt; width) {
    tStr = (/(.*) /, '$1  ');
    tWidth = (tStr);
  }
 
  // ('tStr&gt;width&gt;&gt;tWidth,', tStr, width, tWidth);
  return tStr;
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.