通过canvas api 获取文字宽度
const getTextWidth = () => {
const measureText = document.createElement("canvas");
const ctx = measureText.getContext('2d')!
return (name: string) => {
const { width } = ctx.measureText(name);
return width + 20 + 'px'
}
}
const getWidthByName = getTextWidth()
js 方法(惰性加载)
// 惰性加载
const getTextWidth2 = () => {
let measureText
return (name) => {
if (!measureText) {
measureText = document.createElement("canvas");
}
const ctx = measureText.getContext('2d')
const {width} = ctx.measureText(name);
return width + 20 + 'px'
}
}
const getWidthByName = getTextWidth2()
console.log(getWidthByName('hello'));
console.log(getWidthByName('hello'));
mdn文档