1、為 String 擴展原型方法 byteLength(),該方法將根據每個字符編碼,判斷當前字符是單字節還是雙字節,然后統計字符串的字節長度。
String.prototype.byteLength = function() { var length = 0; Array.from(this).map(function(char){ if(char.charCodeAt(0)>255) {//字符編碼大於255,說明是雙字節字符 length += 2; }else { length++; } }); return length; }
測試:
2、計算文本在頁面所占px寬度 -- 擴展String原型方法pxWidth
/**
* 獲取文本px寬度
* @param font{String}: 字體樣式
**/
String.prototype.pxWidth = function(font) { // re-use canvas object for better performance var canvas = String.prototype.pxWidth.canvas || (String.prototype.pxWidth.canvas = document.createElement("canvas")), context = canvas.getContext("2d"); font && (context.font = font); var metrics = context.measureText(this); return metrics.width; }
測試: