js获取文字渲染实际宽度

6,861次阅读
没有评论

共计 1658 个字符,预计需要花费 5 分钟才能阅读完成。

前言

文字的宽高,不同字体渲染不一样,如何获取字体字号单个文字的实际占用的宽度呢?今天介绍两种方式。

方案一,dom 宽度获取

用真实的 dom 做渲染,然后获取 dom 的宽度,计算得到最终的准确的字符像素长度。

span 方法如下:

  function getStringPixelWidthSpan(text, font) {const span = document.createElement('span');
      document.body.appendChild(span);
      span.style.position = 'absolute';
      span.style.whiteSpace = 'nowrap';
      span.style.font = font;
      span.textContent = text;
      const width = span.offsetWidth;
      document.body.removeChild(span);
      return width;
    }

使用如下:

getStringPixelWidthSpan('haoRooms 博客','20px Microsoft YaHei')

方案二,canvas 获取

function getTextWidth(text, font) {
  // 创建一个临时的 canvas 元素
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');

  // 设置字体样式
  context.font = font;

  // 测量文本的宽度
  var width = context.measureText(text).width;

  // 返回文本的宽度
  return width;
}

使用:

getTextWidth('haoRooms 博客','20px Microsoft YaHei')

获取页面字体

可以通过如下方式获取页面字体

 function getPageFont() {
        // 获取元素的样式
        const htmlStyles = window.getComputedStyle(document.documentElement);

        // 获取 font-family 属性值
        const fontFamily = htmlStyles.getPropertyValue('font-family');

        return fontFamily;
    }

获取效率 canvas 和 span 时间对比

  // Test data
    const textArray = ["你好,世界!", "Hello, World!", "こんにちは、世界!", "안녕하세요, 세상!"];
    const font = "16px Arial";

    // Performance test
    function testPerformance(methodName) {const startTime = performance.now();

      for (let i = 0; i  {if (methodName === 'canvas') {getTextWidth(text, font);
          } else if (methodName === 'span') {getStringPixelWidthSpan(text, font);
          }
        });
      }
      // document.body.removeChild(span);
      const endTime = performance.now();
      const duration = endTime - startTime;
      console.log(`${methodName} method took ${duration.toFixed(2)} milliseconds.`);

    }

// Run performance tests
testPerformance('canvas');
testPerformance('span');

  1000 个时间对比
   canvas method took 10.50 milliseconds.
    span method took 375.50 milliseconds.

结论

canvas 的效果目前看是最好的,推荐使用 canvas 来获取文字渲染实际宽度。

    正文完
     0
    Yojack
    版权声明:本篇文章由 Yojack 于1970-01-01发表,共计1658字。
    转载说明:
    1 本网站名称:优杰开发笔记
    2 本站永久网址:https://yojack.cn
    3 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长进行删除处理。
    4 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
    5 本站所有内容均可转载及分享, 但请注明出处
    6 我们始终尊重原创作者的版权,所有文章在发布时,均尽可能注明出处与作者。
    7 站长邮箱:laylwenl@gmail.com
    评论(没有评论)