Calculate text width with JavaScript

前端 未结 24 1676
陌清茗
陌清茗 2020-11-21 05:08

I\'d like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?

If it\'s not built-in, my only idea is t

相关标签:
24条回答
  • 2020-11-21 05:42

    I like your "only idea" of just doing a static character width map! It actually works well for my purposes. Sometimes, for performance reasons or because you don't have easy access to a DOM, you may just want a quick hacky standalone calculator calibrated to a single font. So here's one calibrated to Helvetica; pass a string and (optionally) a font size:

    function measureText(str, fontSize = 10) {
      const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]
      const avg = 0.5279276315789471
      return str
        .split('')
        .map(c => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg)
        .reduce((cur, acc) => acc + cur) * fontSize
    }
    

    That giant ugly array is ASCII character widths indexed by character code. So this just supports ASCII (otherwise it assumes an average character width). Fortunately, width basically scales linearly with font size, so it works pretty well at any font size. It's noticeably lacking any awareness of kerning or ligatures or whatever.

    To "calibrate" I just rendered every character up to charCode 126 (the mighty tilde) on an svg and got the bounding box and saved it to this array; more code and explanation and demo here.

    0 讨论(0)
  • 2020-11-21 05:42

    In case anyone else got here looking both for a way to measure the width of a string and a way to know what's the largest font size that will fit in a particular width, here is a function that builds on @Domi's solution with a binary search:

    /**
     * Find the largest font size (in pixels) that allows the string to fit in the given width.
     * 
     * @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 ?px verdana") -- note the use of ? in place of the font size.
     * @param {Number} width - The width in pixels the string must fit in
     * @param {Number} minFontPx - The smallest acceptable font size in pixels
     * @param {Number} maxFontPx - The largest acceptable font size in pixels
     **/
    function GetTextSizeForWidth(text, font, width, minFontPx, maxFontPx) {
      for (;;) {
        var s = font.replace("?", maxFontPx);
        var w = GetTextWidth(text, s);
        if (w <= width) {
          return maxFontPx;
        }
    
        var g = (minFontPx + maxFontPx) / 2;
    
        if (Math.round(g) == Math.round(minFontPx) || Math.round(g) == Math.round(maxFontPx)) {
          return g;
        }
    
        s = font.replace("?", g);
        w = GetTextWidth(text, s);
        if (w >= width) {
          maxFontPx = g;
        } else {
          minFontPx = g;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-21 05:43

    The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)

    CSS

    div.places {
      width : 100px;
    }
    div.places span {
      white-space:nowrap;
      overflow:hidden;
    }
    

    HTML

    <div class="places">
      <span>This is my house</span>
    </div>
    <div class="places">
      <span>And my house are your house</span>
    </div>
    <div class="places">
      <span>This placename is most certainly too wide to fit</span>
    </div>
    

    JavaScript (with jQuery)

    // loops elements classed "places" and checks if their child "span" is too long to fit
    $(".places").each(function (index, item) {
        var obj = $(item).find("span");
        if (obj.length) {
            var placename = $(obj).text();
            if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
                var limit = 0;
                do {
                    limit++;
                                        placename = placename.substring(0, placename.length - 1);
                                        $(obj).text(placename + "...");
                } while ($(obj).width() > $(item).width() && limit < 1000)
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-21 05:44

    I wrote a little tool for that. Perhaps it's useful to somebody. It works without jQuery.

    https://github.com/schickling/calculate-size

    Usage:

    var size = calculateSize("Hello world!", {
       font: 'Arial',
       fontSize: '12px'
    });
    
    console.log(size.width); // 65
    console.log(size.height); // 14
    

    Fiddle: http://jsfiddle.net/PEvL8/

    0 讨论(0)
  • 2020-11-21 05:45

    Here's one I whipped together without example. It looks like we are all on the same page.

    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;
    }
    

    Using it is simple: "a string".width()

    **Added white-space: nowrap so strings with width larger than the window width can be calculated.

    0 讨论(0)
  • 2020-11-21 05:45

    This works for me...

    // Handy JavaScript to measure the size taken to render the supplied text;
    // you can supply additional style information too if you have it.
    
    function measureText(pText, pFontSize, pStyle) {
        var lDiv = document.createElement('div');
    
        document.body.appendChild(lDiv);
    
        if (pStyle != null) {
            lDiv.style = pStyle;
        }
        lDiv.style.fontSize = "" + pFontSize + "px";
        lDiv.style.position = "absolute";
        lDiv.style.left = -1000;
        lDiv.style.top = -1000;
    
        lDiv.innerHTML = pText;
    
        var lResult = {
            width: lDiv.clientWidth,
            height: lDiv.clientHeight
        };
    
        document.body.removeChild(lDiv);
        lDiv = null;
    
        return lResult;
    }
    
    0 讨论(0)
提交回复
热议问题