HTML5 Canvas - 文字和字型



HTML5 canvas 提供了使用不同的字型和文字屬性建立文字的功能,如下所示:

序號 屬性和描述
1

font [ = 值 ]

此屬性返回當前字型設定,並且可以設定以更改字型。

2

textAlign [ = 值 ]

此屬性返回當前文字對齊設定,並且可以設定以更改對齊方式。可能的值包括 start、end、left、right 和 center。

3

textBaseline [ = 值 ]

此屬性返回當前基線對齊設定,並且可以設定以更改基線對齊方式。可能的值包括 top、hanging、middle、alphabetic、ideographic 和 bottom。

4

fillText(text, x, y [, maxWidth ] )

此屬性使用給定的座標 x 和 y 在給定位置填充給定的文字。

5

strokeText(text, x, y [, maxWidth ] )

此屬性使用給定的座標 x 和 y 在給定位置描邊給定的文字。

示例

以下是一個簡單的示例,它使用上述屬性來繪製文字:

<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         function drawShape() {
         
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');
            
            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
            
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');
               
               ctx.fillStyle = '#00F';
               ctx.font = 'Italic 30px Sans-Serif';
               
               ctx.textBaseline = 'Top';
               ctx.fillText('Hello world!', 40, 100);
               
               ctx.font = 'Bold 30px Sans-Serif';
               ctx.strokeText('Hello world!', 40, 50);
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
   
</html>

以上示例將產生以下結果:

html5_canvas.htm
廣告