我想使用JavaScript来计算字符串的宽度。如果不使用单行字体,这可能吗?

如果它不是内置的,我唯一的想法是为每个字符创建一个宽度表,但这是非常不合理的,特别是支持Unicode和不同的类型大小(以及所有浏览器)。


当前回答

ExtJS javascript库中有一个很棒的类,叫做Ext.util.TextMetrics,它“为文本块提供精确的像素测量,这样你就可以准确地确定给定文本块的高和宽(以像素为单位)”。您可以直接使用它,也可以查看它的源代码以了解如何完成此操作。

http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html

其他回答

如果你可以安装一个包,并且你想要一个更权威或更精确的答案,你可以使用opentype.js(奇怪的是没有人提到这一点):

import { load } from "opentype.js";

const getWidth = async (text = "Hello World") => {
  const font = await load("path/to/some/font");
  const { x1, x2 } = font.getPath(text, 0, 0, 12).getBoundingBox();
  return x2 - x1;
};

当然,您希望每个字体只调用load一次,因此应该根据您的情况将该行拉出到更高的范围。

下面是一个代码沙盒,将OpenType方法与Canvas和DOM方法进行比较: https://codesandbox.io/s/measure-width-of-text-in-javascript-vctst2

在我的机器上,每个100个样品,典型的结果是:

女士的OpenType: 5 女士帆布:3 女士DOM: 4

我发现的另一个软件包是:https://github.com/sffc/word-wrappr

jQuery:

(function($) {

 $.textMetrics = function(el) {

  var h = 0, w = 0;

  var div = document.createElement('div');
  document.body.appendChild(div);
  $(div).css({
   position: 'absolute',
   left: -1000,
   top: -1000,
   display: 'none'
  });

  $(div).html($(el).html());
  var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
  $(styles).each(function() {
   var s = this.toString();
   $(div).css(s, $(el).css(s));
  });

  h = $(div).outerHeight();
  w = $(div).outerWidth();

  $(div).remove();

  var ret = {
   height: h,
   width: w
  };

  return ret;
 }

})(jQuery);

这是我随手拼凑的一个例子。看来我们都达成共识了。

String.prototype.width = function(font) {
  var f = font || '12px arial',
      o = $('<div></div>')
            .text(this)
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}

使用它很简单:"a string".width()

**增加了空格:nowrap,因此宽度大于窗口宽度的字符串可以被计算。

没有jQuery:

String.prototype.width = function (fontSize) {
    var el,
        f = fontSize + " px arial" || '12px arial';
    el = document.createElement('div');
    el.style.position = 'absolute';
    el.style.float = "left";
    el.style.whiteSpace = 'nowrap';
    el.style.visibility = 'hidden';
    el.style.font = f;
    el.innerHTML = this;
    el = document.body.appendChild(el);
    w = el.offsetWidth;
    el.parentNode.removeChild(el);
    return w;
}

// Usage
"MyString".width(12);
var textWidth = (function (el) {
    el.style.position = 'absolute';
    el.style.top = '-1000px';
    document.body.appendChild(el);

    return function (text) {
        el.innerHTML = text;
        return el.clientWidth;
    };
})(document.createElement('div'));