如何计算JavaScript中字符串文本的宽度

您所在的位置:网站首页 js获取文字内容宽度 如何计算JavaScript中字符串文本的宽度

如何计算JavaScript中字符串文本的宽度

2024-07-14 22:46| 来源: 网络整理| 查看: 265

JS计算字符串文本的宽度 在使用canvas制作动画时,经常需要获取字符串的宽度与边缘进行对比,以下是通过js来获取任意字符串宽度的方法:

function getTextWidth(text, fontSize) { // 创建临时元素 const _span = document.createElement(‘span’) // 放入文本 _span.innerText = text // 设置文字大小 _span.style.fontSize = fontSize + ‘px’ // span元素转块级 _span.style.position = ‘absolute’ // span放入body中 document.body.appendChild(_span) // 获取span的宽度 let width = _span.offsetWidth // 从body中删除该span document.body.removeChild(_span) // 返回span宽度 return width }

JS计算任意字符串宽度 PS: 是宽度不是长度!

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

这里提供几种比较测量方法:

1.通过 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.@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) { // 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 = contexasureText(text); return metrics.width; }

console.log(getTextWidth(“hello there!”, “bold 12pt arial”)); // close to 86

2.通过 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; }

3.用个 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 contexasureText(text).width; }

addStrWidthViaBlank(str, width) { // 这个函数只适用于’xxx xx’形式的字符串(即原串就含有空格) if (width = 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; }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3