HTML Canvas - fillText() 方法



HTML Canvas 的 fillText() 方法可以用來在 Canvas 元素上指定座標處繪製文字字串,並使用當前的 fillStyle 屬性。

它在 CanvasRenderingContext2D 介面中可用,並填充上下文物件繪製的文字。

語法

以下是 HTML Canvas fillText() 方法的語法:

CanvasRenderingContext2D.fillText(text, x, y, text_width)

引數

以下是此方法的引數列表:

序號 引數及描述
1 text

要渲染到 Canvas 元素上的文字字串。

2 x

在 Canvas 元素中繪製文字的起始點的 x 座標。

3 y

在 Canvas 元素中繪製文字的起始點的 y 座標。

4 text_width

要繪製的文字寬度(以畫素為單位)。

返回值

它會在 Canvas 元素上渲染作為引數傳遞的字串。

示例 1

以下示例使用 HTML Canvas fillText() 方法在 Canvas 元素上繪製一個字串。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="300" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "40px Verdana";
      context.fillText('TutorialsPoint', 20, 50);
   </script>
</body>
</html>

輸出

上述程式碼在網頁上返回的輸出如下:

HTML Canvas FillText Method

示例 2

以下程式碼使用 fillText() 方法將一個句子字串新增到 Canvas 元素中,並且沒有使用 font 屬性。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="370" height="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.font = "10px Verdana";
      context.fillText('This text is written on the canvas element using fillText() method', 20, 50);
   </script>
</body>
</html>

輸出

上述程式碼在網頁上返回的輸出如下:

HTML Canvas FillText Method
html_canvas_text.htm
廣告

© . All rights reserved.