JS计算文本字符串字节长度和像素长度的方法


来源:js获取字符长度并计算px宽度 - 【云】风过无痕 - 博客园 (cnblogs.com)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS计算文本字符串长度的两种方法</title>
</head>

<body>
    <span style="font:normal 36px Robot;">qwe</span>
</body>

<script>
    // 字节长度
    String.prototype.byteLength = function () {
        var length = 0;
        Array.from(this).map(function (char) {
            // 字符编码大于255,说明是双字节字符
            if (char.charCodeAt(0) > 255) {
                length += 2;
            } else {
                length++;
            }
        });

        return length;
    }
    // 获取文本px宽度* @param font{String}: 字体样式    eg: normal 36px Robot
    String.prototype.pxWidth = function (font) {
        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;
    }
</script>

</html>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM