JavaScript计算字符串文本的宽度

在使用canvas制作动画时,经常需要获取字符串的宽度与边缘进行对比,以下是通过js来获取任意字符串宽度的方法:

function getTextWidth(text, fontSize) {
// 创建临时元素
const _span = document.createElement('span')
// 放入文本
_span.innerText = text
// 设置文字大小
_span.style.fontSize = fontSize + 'px'
// span元素转块级
_span.style.position = 'absolute'
// span放入body中
document.body.appendChild(_span)
// 获取span的宽度
let width = _span.offsetWidth
// 从body中删除该span
document.body.removeChild(_span)
// 返回span宽度
return width
}



————————————————
转:https://blog.csdn.net/ywl_156/article/details/122320772

posted @ 2022-03-12 14:24  rmticocean  阅读(475)  评论(0编辑  收藏  举报