首页 > 开发 > HTML5 > 正文

HTML5 Canvas的文本度量

2024-09-05 07:18:40
字体:
来源:转载
供稿:网友
目前,文本的宽度是唯一的度量与measureText()的方法 。目前还不支持文本的高度公制。

 


<!DOCTYPE HTML>

<html>

    <head>

        <style>

            body {

                margin: 0px;

                padding: 50px;

            }
            #myCanvas {
                border: 1px solid #9C9898;
            }
        </style>

        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                var x = canvas.width / 2;
                var y = canvas.height / 2 - 10;
                var text = "Hello World!";

                context.font = "30pt Calibri";
                context.textAlign = "center";
                context.fillStyle = "blue";
                context.fillText(text, x, y);
                // get text metrics
                var metrics = context.measureText(text);
                var width = metrics.width;
                context.font = "20pt Calibri";
                context.textAlign = "center";
                context.fillStyle = "#555";
                context.fillText("(" + width + "px wide)", x, y + 40);
            };
        </script>
    </head>
    <body onmousedown="return false;">
        <canvas id="myCanvas" width="578" height="200">
        </canvas>
    </body>
</html>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表