js获取字符长度并计算px宽度

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; }

 测试:

 

posted @ 2020-10-27 10:14  【云】风过无痕  阅读(11508)  评论(0编辑  收藏  举报