美文网首页
js 计算文字及符号宽度

js 计算文字及符号宽度

作者: 胡小喵_ | 来源:发表于2023-10-07 15:33 被阅读0次

js 中英文字符以及标点符号宽度会有所不同,导致 canvas 无法直接用fontSize计算内容宽度,可以用以下方法获取文字的真实宽度。

const getLetterWidth = (letter, fontSize) => {
    const dom = document.createElement('span');
    dom.style.display = 'inline-block';
    dom.style.fontSize = fontSize + 'px';
    dom.textContent = letter;
    document.body.appendChild(dom);
    const width = dom.getBoundingClientRect().width;
    dom.remove();
    return Number(width.toFixed(2));
};

相关文章

网友评论

      本文标题:js 计算文字及符号宽度

      本文链接:https://www.haomeiwen.com/subject/zrhvbdtx.html