measure text width

Benchmark created on


Preparation HTML

<span id="aeolus-text-ruler"></span>
  <canvas id="aeolus-text-canvas-ruler"></canvas>

Setup

var fontFamily = ''
    var getFontFamily = () => {
      fontFamily = getComputedStyle(document.body).fontFamily
    }
    getFontFamily()
    var calcTextVisualWidth = function (text, fontSize) {
      var ruler = document.getElementById('aeolus-text-ruler');
      if (!ruler) {
        ruler = document.createElement('span');
        ruler.setAttribute('id', 'aeolus-text-ruler');
        ruler.setAttribute('style', 'visibility: hidden; white-space: nowrap; position: fixed; bottom: -999px;');
        document.body.appendChild(ruler);
      }
      if (ruler.style.fontSize !== "".concat(fontSize, "px"))
        ruler.style.fontSize = "".concat(fontSize, "px");

      ruler.innerText = text;
      return ruler.offsetWidth;
    };

    var calcTextVisualWidth2 = function (text, fontSize) {
      var canvas = document.getElementById('aeolus-text-canvas-ruler');
      var context = canvas.getContext('2d');
      context.font = "".concat(fontSize, "px") + ' ' + fontFamily;
      var metrics = context.measureText(text);
      return metrics.width;
    };

Test runner

Ready to run.

Testing in
TestOps/sec
use dom
calcTextVisualWidth(`结果会显示每个测试用例的运行速度,单位是 "operations/second",数值越大表示性能越好`);
ready
use canvas
calcTextVisualWidth2(`结果会显示每个测试用例的运行速度,单位是 "operations/second",数值越大表示性能越好`)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.