Calculate text width with JavaScript

前端 未结 24 1612
陌清茗
陌清茗 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

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

提交回复
热议问题