通过canvas方法计算任意字符串所占的实际宽度 | 您所在的位置:网站首页 › 微信测量长度 › 通过canvas方法计算任意字符串所占的实际宽度 |
目录
1. 法一 使用canvas画布。`getContext("2d")`方法`measureText()方法`项目应用
法二 通过DOM测量textContent() 方法设置文本内容 + clientWidth值
法三 用 visibility: hidden 的浮动的层来计算字符串宽度。
js计算任意字符串宽度
由于像素和字体大小,字节(特别是 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 = contexasureText(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"); // 其他代码 }2D 上下文提供了用于辅助确定文本大小的 measureText()方法。这个方法接收一个参数,即要绘制的文本,然后返回一个TextMetrics对象。这个返回的对象目前只有一个属性width,不过将来应该会增加更多度量指标。 measureText()方法使用 font、textAlign 和 textBaseline 属性当前的值计算绘制指定文本后的大小。 用在我的aizoo项目中, 用于节点的title宽度设置, 用于设置节点的min-width 通过 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值
在添加的 div 容器里把样式设置为和你实际的 div 一样。 var str = 'Live like you were dying, Love because you do.'; str = str.substring(0, str.length); $('#labelText').css({ 'font-size': '12px', 'font-family': 'Microsoft YaHei' }).html(str); var width = $('#labelText').width(); console.log(width);计算高度也一样。 最后别忘了移除额外添加的 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 contexasureText(text).width; } addStrWidthViaBlank(str, width) { // 这个函数只适用于'xxx xx'形式的字符串(即原串就含有空格) if (width = width)) { return str; } let tStr = str; let tWidth = 0; while (tWidth |
CopyRight 2018-2019 实验室设备网 版权所有 |