JavaScript中如何計算字符串文本的寬度
JS計算字符串文本的寬度
在使用canvas制作動畫時,經(jīng)常需要獲取字符串的寬度與邊緣進行對比,以下是通過js來獲取任意字符串寬度的方法:
function getTextWidth(text, fontSize) { // 創(chuàng)建臨時元素 const _span = document.createElement('span') // 放入文本 _span.innerText = text // 設(shè)置文字大小 _span.style.fontSize = fontSize + 'px' // span元素轉(zhuǎn)塊級 _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: 是寬度不是長度!
由于像素和字體大小,字節(jié)(特別是 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 = context.measureText(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 容器里把樣式設(shè)置為和你實際的 div 一樣。
<!DOCTYPE html> <html>? <head> ? <script src='jquery.min.js'></script> </head> <body> ? <div ? ? id='labelText'? ? ? style='color:black; line-height:1.2; white-space: nowrap; position:fixed; ? ? ? top:0px; left:0px; display:block; visibility:visible;' ? ></div> ? ? <script> ? ? 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); ? </script> </body> </html>
計算高度也一樣。
最后別忘了移除額外添加的 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) { // 這個函數(shù)只適用于'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; }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript實現(xiàn)url地址自動檢測并添加URL鏈接示例代碼
寫一個簡單的聊天系統(tǒng),發(fā)出Htpp的Url實現(xiàn)跳轉(zhuǎn)加上a標簽,下面是具體的實現(xiàn),感興趣的朋友不要錯過2013-11-11使用ImageMagick進行圖片縮放、合成與裁剪(js+python)
由于需要在服務(wù)器端處理,使用就研究使用imagemagick來進行。同時準備封裝了一個Node.js和Python的方法,主要還是講一下然后使用imagemagick來對圖片進行縮放、合成后進行裁剪吧2013-09-09