Calculate text width with JavaScript

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

    I'm using text-metrics package. Works really nice, I tried this solution but in some reasons, it counts it wrong.

    textMetrics.init(document.querySelector('h1'), { fontSize: '20px' });
    
    textMetrics.init({
      fontSize: '14px',
      lineHeight: '20px',
      fontFamily: 'Helvetica, Arial, sans-serif',
      fontWeight: 400,
      width: 100,
    });
    

提交回复
热议问题