JS根据文本内容计算占用宽度
/**
* 使用canvas
* @param {String} text 文本
* @param {String} font 字体 如 'normal 12px Arial'
*/
function getTextWidth(text, font) {
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"))
const context = canvas.getContext("2d")
context.font = font
const metrics = context.measureText(text)
return metrics.width
}
console.log(getTextWidth('IT sol-implementation M', 'normal 12px Arial')); // 118.4521484375