通过canvas方法计算任意字符串所占的实际宽度
发布日期:2021-05-14 11:07:15 浏览次数:20 分类:精选文章

本文共 2884 字,大约阅读时间需要 9 分钟。

目录

由于像素和字体大小,字节(特别是 UTF-8)等限制因素,所以我们不能直接知道一个字符串所占的实际宽度。

1. 法一 使用canvas画布。

测量文本以计算并返回给定字体的给定文本的宽度(以像素为单位)。

/** * 使用canvas画布。测量文本以计算并返回给定字体的给定文本的宽度(以像素为单位)。 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels. * 要呈现的文本 * @param {String} text The text to be rendered. * 用于呈现文本的css字体描述符 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana"). *  * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393 */function getTextWidth(text, font) {     // 重用canvas对象以获得更好的性能  // re-use canvas object for better performance  var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));  var context = canvas.getContext("2d");   // console.log('context=', context) 获得对绘图上下文canvas的引用  context.font = font  var metrics = context.measureText(text)  console.log('metrics=', metrics)  return metrics.width;} console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86

getContext("2d")方法

要在画布上绘制图形,首先要取得绘图上下文。使用 getContext()方法可以获取对绘图上下文的引用。对于平面图形,需要给这个方法传入参数"2d",表示要获取 2D 上下文对象:

let drawing = document.getElementById("drawing"); // 确保浏览器支持
if (drawing.getContext) { let context = drawing.getContext("2d"); // 其他代码}

在这里插入图片描述

在这里插入图片描述

measureText()方法

2D 上下文提供了用于辅助确定文本大小的 measureText()方法。这个方法接收一个参数,即要绘制的文本,然后返回一个TextMetrics对象。这个返回的对象目前只有一个属性width,不过将来应该会增加更多度量指标。

measureText()方法使用 fonttextAligntextBaseline 属性当前的值计算绘制指定文本后的大小。
在这里插入图片描述
在这里插入图片描述

Your browser does not support the HTML5 canvas tag.

在这里插入图片描述

项目应用

用在我的aizoo项目中, 用于节点的title宽度设置, 用于设置节点的min-width

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

法二 通过DOM测量

通过 DOM 测量,这种方法在字符串中含有多个空格时,测出来的宽度会一样,

例如: ‘‘天猫旗舰店 49.67%(tmall)’’ 和 ‘‘天猫旗舰店 49.67%(tmall)’’ 测出来的宽度都为 165(此值可能会有差异)

function getTextWidth(str = '') {     const dom = document.createElement('span');  dom.style.display = 'inline-block';  dom.textContent = '天猫旗舰店   49.67%(tmall)';  document.body.appendChild(dom);  const width = dom.clientWidth;  console.log(dom.clientWidth);  document.body.removeChild(dom);  return width;}

textContent() 方法设置文本内容 + clientWidth值

在这里插入图片描述

在这里插入图片描述

法三 用 visibility: hidden 的浮动的层来计算字符串宽度。

在添加的 div 容器里把样式设置为和你实际的 div 一样。

     

计算高度也一样。

最后别忘了移除额外添加的 div

Code:

let tCanvas = null;getTextWidth(text, font = 'normal 12px sans-serif') {     // re-use canvas object for better performance  const canvas = tCanvas || (tCanvas = document.createElement('canvas'));  const context = canvas.getContext('2d');  context.font = font;  return context.measureText(text).width;} addStrWidthViaBlank(str, width) {     // 这个函数只适用于'xxx xx'形式的字符串(即原串就含有空格)  if (width <= 0 || (this.getTextWidth(str) >= width)) {       return str;  }   let tStr = str;  let tWidth = 0;  while (tWidth < width) {       tStr = tStr.replace(/(.*) /, '$1  ');    tWidth = this.getTextWidth(tStr);  }   // console.log('tStr>width>>tWidth,', tStr, width, tWidth);  return tStr;}
上一篇:node控制多行输入输出
下一篇:javascript数据结构与算法-链表

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年05月04日 20时42分34秒