JavaScript中如何計(jì)算字符串文本的寬度
JS計(jì)算字符串文本的寬度
在使用canvas制作動(dòng)畫時(shí),經(jīng)常需要獲取字符串的寬度與邊緣進(jìn)行對(duì)比,以下是通過(guò)js來(lái)獲取任意字符串寬度的方法:
function getTextWidth(text, fontSize) { // 創(chuàng)建臨時(shí)元素 const _span = document.createElement('span') // 放入文本 _span.innerText = text // 設(shè)置文字大小 _span.style.fontSize = fontSize + 'px' // span元素轉(zhuǎn)塊級(jí) _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計(jì)算任意字符串寬度
PS: 是寬度不是長(zhǎng)度!
由于像素和字體大小,字節(jié)(特別是 UTF-8)等限制因素,所以我們不能直接知道一個(gè)字符串所占的實(shí)際寬度。
這里提供幾種比較測(cè)量方法:
1.通過(guò) Canvas 測(cè)量
/** ?* 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.通過(guò) DOM 測(cè)量
這種方法在字符串中含有多個(gè)空格時(shí),測(cè)出來(lái)的寬度會(huì)一樣,
例如: ''天貓旗艦店 49.67%(tmall)'' 和 ''天貓旗艦店 49.67%(tmall)'' 測(cè)出來(lái)的寬度都為 165(此值可能會(huì)有差異)
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.用個(gè) visibility: hidden
的浮動(dòng)的層來(lái)計(jì)算字符串寬度。
在添加的 div 容器里把樣式設(shè)置為和你實(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>
計(jì)算高度也一樣。
最后別忘了移除額外添加的 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) { // 這個(gè)函數(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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
淺談使用MVC模式進(jìn)行JavaScript程序開發(fā)
這篇文章主要介紹了淺談使用MVC模式進(jìn)行JavaScript程序開發(fā),同時(shí)也介紹了一些JavaScript的MVC框架,需要的朋友可以參考下2015-11-11JavaScript實(shí)現(xiàn)url地址自動(dòng)檢測(cè)并添加URL鏈接示例代碼
寫一個(gè)簡(jiǎn)單的聊天系統(tǒng),發(fā)出Htpp的Url實(shí)現(xiàn)跳轉(zhuǎn)加上a標(biāo)簽,下面是具體的實(shí)現(xiàn),感興趣的朋友不要錯(cuò)過(guò)2013-11-11純?cè)鷍s實(shí)現(xiàn)table表格的增刪
本文主要介紹了純?cè)鷍avascript實(shí)現(xiàn)table表格的增刪的方法,文章底部提供了完整的代碼。需要的朋友一起來(lái)看下吧2017-01-01使用ImageMagick進(jìn)行圖片縮放、合成與裁剪(js+python)
由于需要在服務(wù)器端處理,使用就研究使用imagemagick來(lái)進(jìn)行。同時(shí)準(zhǔn)備封裝了一個(gè)Node.js和Python的方法,主要還是講一下然后使用imagemagick來(lái)對(duì)圖片進(jìn)行縮放、合成后進(jìn)行裁剪吧2013-09-09