使用 js 获取文本宽度
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
}
通过创建 div,然后获取宽度
function getTextWidth(text, font) {
var span = document.createElement("span");
span.style.font = font;
span.innerHTML = text;
document.body.appendChild(span);
var width = span.offsetWidth;
document.body.removeChild(span);
return width;
}