JavaScript中如何計(jì)算字符串文本的寬度
JS計(jì)算字符串文本的寬度
在使用canvas制作動(dòng)畫時(shí),經(jīng)常需要獲取字符串的寬度與邊緣進(jìn)行對(duì)比,以下是通過js來獲取任意字符串寬度的方法:
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: 是寬度不是長度!
由于像素和字體大小,字節(jié)(特別是 UTF-8)等限制因素,所以我們不能直接知道一個(gè)字符串所占的實(shí)際寬度。
這里提供幾種比較測(cè)量方法:
1.通過 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 862.通過 DOM 測(cè)量
這種方法在字符串中含有多個(gè)空格時(shí),測(cè)出來的寬度會(huì)一樣,
例如: ''天貓旗艦店 49.67%(tmall)'' 和 ''天貓旗艦店 49.67%(tmall)'' 測(cè)出來的寬度都為 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)的層來計(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)文章
解決微信瀏覽器Javascript無法使用window.location.reload()刷新頁面
這篇文章主要介紹在微信瀏覽器Javascript無法使用window.location.reload()刷新頁面的解決方法,比較實(shí)用,需要的朋友可以參考下。2016-06-06
JS結(jié)合WebSocket實(shí)現(xiàn)實(shí)時(shí)雙向通信
WebSocket 是一種在 Web 應(yīng)用程序中實(shí)現(xiàn)實(shí)時(shí)、雙向通信的協(xié)議,在本文中,我們將深入介紹 WebSocket 的原理、用法以及一些實(shí)際應(yīng)用場(chǎng)景,x需要的可以參考下2023-11-11
JavaScript實(shí)現(xiàn)旋轉(zhuǎn)木馬輪播圖
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)旋轉(zhuǎn)木馬輪播圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
深入理解ES6之?dāng)?shù)據(jù)解構(gòu)的用法
本文介紹了深入理解ES6之?dāng)?shù)據(jù)解構(gòu)的用法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01
iframe的onreadystatechange事件在firefox下的使用
firefox不支持iframe的onreadystatechange事件,不過有個(gè)方法可以實(shí)現(xiàn)同等的效果,需要的朋友可以參考下2014-04-04
Bootstrap基本組件學(xué)習(xí)筆記之縮略圖(13)
這篇文章主要為大家詳細(xì)介紹了Bootstrap基本組件學(xué)習(xí)筆記之縮略圖,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12

