DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> HTML基礎知識 >> HTML和Xhtml >> HTML5 Canvas的文本度量
HTML5 Canvas的文本度量
編輯:HTML和Xhtml     

要獲得HTML5 Canvas的文本度量,我們可以使用的measureText()的畫布上下文的方法 。這種方法需要一個文本字符串,並返回一個度量對象的基礎上提供的文本,並分配給上下文的當前文本的字體。

  1. var metrics = context.measureText(text);
  2. var width = metrics.width;
目前,文本的寬度是唯一的度量與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>

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved