HTML Canvas - stroke() 方法



HTML Canvas 的 stroke() 方法用於在給定路徑或任何形狀的輪廓上新增描邊。

它預設使用黑色為路徑新增描邊,並且還會搜尋由 strokeStyle 屬性給定的輸入顏色,並使用此顏色輸入代替黑色。

語法

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

CanvasRenderingContext2D.stroke(path);

引數

以下是此方法使用的引數:

序號 引數及說明
1 path

用於應用 stroke() 方法的路徑。

返回值

應用了 stroke() 方法的路徑,在 Canvas 元素內使用黑色進行描邊。如果存在 strokeStyle 屬性,則使用其中傳遞的顏色對路徑進行描邊。

示例 1

以下示例使用 HTML Canvas stroke() 方法在 Canvas 元素上為矩形新增描邊。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Reference API</title>
   <style>
      body {
         margin: 10px;
         padding: 10px;
      }
   </style>
</head>
<body>
   <canvas id="canvas" width="250" height="150" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.rect(25, 25, 150, 100);
      context.stroke();
   </script>
</body>
</html>

輸出

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

HTML Canvas Stroke Method

示例 2

以下示例首先建立一個空路徑,並使用 lineTo() 方法繪製一個三角形,然後使用 stroke() 方法和 strokeStyle 屬性中指定的顏色為 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="200" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      context.beginPath();
      context.strokeStyle = 'green';
      context.moveTo(150, 50);
      context.lineTo(50, 150);
      context.lineTo(250, 150);
      context.closePath();
      context.stroke();
   </script>
</body>
</html>

輸出

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

HTML Canvas Stroke Method
html_canvas_paths.htm
廣告

© . All rights reserved.