HTML Canvas - strokeStyle 屬性



HTML Canvas strokeStyle 屬性由 Canvas 2D API 中的介面 CanvasRenderingContext2D 使用,它使用 Canvas 元素的上下文物件,並用提供的顏色為描邊的圖形上色。

它主要指定用於向任何形狀新增描邊的顏色、漸變或圖案。預設顏色為“黑色”。

可能的輸入值

此屬性接受以下任意一個值:

  • 任何格式的 CSS 顏色值。

  • 用於在形狀內部新增的漸變物件。

  • 用於在形狀內部建立重複圖案的圖案物件。

例項

以下示例使用由 HTML Canvas strokeStyle 屬性傳遞的顏色名稱向由 CanvasRenderingContext2D 物件建立的矩形新增描邊。

<!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="250" style="border: 1px solid black;"></canvas>
      <script>
         var canvas = document.getElementById("canvas");
         var context = canvas.getContext('2d');
         context.strokeStyle = 'grey';
         context.rect(20, 20, 250, 200);
         context.stroke();
      </script>
   </body>
</html>

輸出

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

HTML Canvas StrokeStyle Property

例項

以下示例使用 RGB 顏色值向由 CanvasRenderingContext2D 物件建立的矩形新增描邊。

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

輸出

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

HTML Canvas StrokeStyle Property
html_canvas_rectangles.htm
廣告