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