HTML Canvas - fillStyle 屬性



HTML Canvas 的fillStyle 屬性來自 Canvas 2D API 的CanvasRenderingContext2D 介面,它接收上下文物件形狀,並用傳入的顏色值填充它。

它主要指定在任何形狀內部使用的顏色、漸變或圖案。預設顏色為“黑色”。

可能的輸入值

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

  • 任何格式的 CSS 顏色值。

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

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

示例

下面的程式在 Canvas 元素內繪製一個矩形,並使用 HTML Canvas 的fillStyle 屬性進行填充。

<!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.fillStyle = 'blue';
         context.rect(35, 35, 200, 150);
         context.fill();
      </script>
   </body>
</html>

輸出

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

HTML Canvas FillStyle Property

示例

下面的程式在 Canvas 元素內繪製一個矩形,並使用fillStyle 屬性填充一個建立的圖案。

<!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; background-color: blue;"></canvas>
      <script>
         var canvas = document.getElementById('canvas');
         var context = canvas.getContext('2d')
         var image = new Image();
         image.src = 'https://tutorialspoint.tw/themes/home/tp-diamond-logo-white.png';
         image.onload = function() {
            var pattern = context.createPattern(image, 'repeat');
            context.fillStyle = pattern;
            context.fillRect(0, 0, canvas.width, canvas.height);
         }
      </script>
   </body>
</html>

輸出

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

HTML Canvas FillStyle Property

示例

下面的程式在 Canvas 元素內繪製一個矩形,並使用fillStyle 屬性填充一個漸變物件。

<!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');
         var lineargrad = context.createLinearGradient(0, 0, 200, 100);
         context.fillStyle = lineargrad;
         lineargrad.addColorStop(0, 'cyan');
         lineargrad.addColorStop(0.5, 'white');
         lineargrad.addColorStop(1, 'purple');
         context.fillRect(10, 10, 250, 200);
      </script>
   </body>
</html>

輸出

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

HTML Canvas FillStyle Property
html_canvas_rectangles.htm
廣告
© . All rights reserved.