Canvas Text

Canvas Text (画布文字)

HTML5 canvas allows creating text using different font and text properties presented below:

Properties and Methods

Properties and Methods (属性和方法)

PropertyDescription
fontIt returns the current font settings and can be set to change the font.
textAlignIt returns the current text alignment settings and can be set to change the alignment. The property has the following values: start, end, left, right, and center.
textBaselineIt returns the current baseline alignment settings and can be set to change the baseline alignment. The property has the following values: top, hanging, middle, alphabetic, ideographic, and bottom.
fillText(text, x, y)It draws a filled text at the position indicated by the given coordinates x and y.
strokeText(text, x, y)It strokes the text at the position indicated by the given coordinates x and y.

Example of the fillText() property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
 </head>
 <body>
   <canvas id="exampleCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
     Your browser does not support the canvas element.
(您的浏览器不支持画布元素。)
   </canvas>
   <script>
     var canvas = document.getElementById("exampleCanvas");

     var ctx = canvas.getContext("2d");

     ctx.font = "30px Arial";

     ctx.fillText("Hello World", 70, 80);

   </script>
 </body>
</html>

Example of the textStroke() property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
 </head>
 <body>
   <canvas id="exampleCanvas" width="250" height="150" style="border:1px solid #d3d3d3;">
     Your browser does not support the canvas element.
(您的浏览器不支持画布元素。)
   </canvas>
   <script>
     var canvas = document.getElementById("exampleCanvas");

     var ctx = canvas.getContext("2d");

     ctx.font = "27px Arial";

     ctx.strokeText("Canvas text", 40, 70);

   </script>
 </body>
</html>

Example of adding color and centering text:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the document</title>
 </head>
 <body>
   <canvas id="exampleCanvas" width="400" height="250" style="border:1px solid #d3d3d3;">
     Your browser does not support the canvas element.
(您的浏览器不支持画布元素。)
   </canvas>
   <script>
     var canvas = document.getElementById("exampleCanvas");

     var ctx = canvas.getContext("2d");

     ctx.font = "40px Comic Sans MS";

     ctx.fillStyle = "red";

     ctx.textAlign = "center";

     ctx.fillText("Canvas Text", canvas.width / 2, canvas.height / 2);

   </script>
 </body>
</html>


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部