js 計算文字寬度


 

方式1 利用canvas處理

/*
計算文字寬度
text 需要計算寬度的文字 包括空格
font 字體屬性  比如  `12px sans-serif`
*/
function getTextWidth(text, font) {
    // getTextWidth.canvas 這里主要為了復用一個canvas   getTextWidth.canvas就是一個全局變量
    // getTextWidth.任意變量 首次定義只能在getTextWidth函數內定義
    // 然后在其他函數內就可以定義 getTextWidth.其他變量  但是不建議這么使用 
    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;
}

方式2 利用頁面控件處理

<html>
<head>
<style type="text/css">
#ruler {
    position:absolute;
    visibility: hidden;
    white-space: nowrap;
    z-index: -900;
    /* white-space: pre 為了處理多空格計算寬度小的問題 */
    white-space: pre;
}
</style>
</head>
<body>
  <span id="ruler"></span>
<script type="text/javascript">
function(text, size, family) {
   var ruler = document.getElementById("ruler");
   ruler.style.fontSize = size;
   ruler.style.fontFamily = family;
  ruler.textContent = text;
 return ruler.clientWidth;
}
</script>
</body>
</html>

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM