JavaScript中如何计算字符串文本的宽度?

JS计算字符串文本的宽度

在使用canvas制作动画时,经常需要获取字符串的宽度与边缘进行对比,以下是通过js来获取任意字符串宽度的方法:

function getTextWidth(text, fontSize) {
        // 创建临时元素
        const _span = document.createElement('span')
        // 放入文本
        _span.innerText = text
        // 设置文字大小
        _span.style.fontSize = fontSize + 'px'
        // span元素转块级
        _span.style.position = 'absolute'
        // span放入body中
        document.body.appendChild(_span)
        // 获取span的宽度
        let width = _span.offsetWidth
        // 从body中删除该span
        document.body.removeChild(_span)
        // 返回span宽度
        return width
}

JS计算任意字符串宽度

PS: 是宽度不是长度!

由于像素和字体大小,字节(特别是 UTF-8)等限制因素,所以我们不能直接知道一个字符串所占的实际宽度。

这里提供几种比较测量方法:

1.通过 Canvas 测量

/**
 * Uses canvas.measureText 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 (e.g. "bold 14px verdana").
 * 
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, font) {
  // re-use canvas object for better performance
  var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
  var context = canvas.getContext("2d"); 
  context.font = font;
  var metrics = context.measureText(text);
  return metrics.width;
}
 
console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86

2.通过 DOM 测量

这种方法在字符串中含有多个空格时,测出来的宽度会一样,

例如: ''天猫旗舰店 49.67%(tmall)'' 和 ''天猫旗舰店 49.67%(tmall)'' 测出来的宽度都为 165(此值可能会有差异)

function getTextWidth(str = '') {
  const dom = document.createElement('span');
  dom.style.display = 'inline-block';
  dom.textContent = '天猫旗舰店   49.67%(tmall)';
  document.body.appendChild(dom);
  const width = dom.clientWidth;
  console.log(dom.clientWidth);
  document.body.removeChild(dom);
  return width;
}

3.用个 visibility: hidden

的浮动的层来计算字符串宽度。

在添加的 div 容器里把样式设置为和你实际的 div 一样。

<!DOCTYPE html>
<html> 
<head>
  <script src='jquery.min.js'></script>
</head>
<body>
  <div
     
    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 = str.substring(0, str.length);
    $('#labelText').css({
      'font-size': '12px',
      'font-family': 'Microsoft YaHei'
    }).html(str);
    var width = $('#labelText').width();
    console.log(width);
  </script>
</body>
</html>

计算高度也一样。

最后别忘了移除额外添加的 div!

Code:

let tCanvas = null;
getTextWidth(text, font = 'normal 12px sans-serif') {
  // re-use canvas object for better performance
  const canvas = tCanvas || (tCanvas = document.createElement('canvas'));
  const context = canvas.getContext('2d');
  context.font = font;
  return context.measureText(text).width;
}
 
addStrWidthViaBlank(str, width) {
  // 这个函数只适用于'xxx xx'形式的字符串(即原串就含有空格)
  if (width <= 0 || (this.getTextWidth(str) >= width)) {
    return str;
  }
 
  let tStr = str;
  let tWidth = 0;
  while (tWidth < width) {
    tStr = tStr.replace(/(.*) /, '$1  ');
    tWidth = this.getTextWidth(tStr);
  }
 
  // console.log('tStr>width>>tWidth,', tStr, width, tWidth);
  return tStr;
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/ywl_156/article/details/122320772