Skip to content

JS 获取文本宽度

Published: at 04:44 PMSuggest Changes

使用 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;
}

Previous Post
Mac 系统下快速删除 node_modules 文件夹
Next Post
JS 图片处理研究笔记