HTML Canvas - addColorStop() 方法



HTML Canvas 的addColorStop()方法可以用來向Canvas元素上渲染的圖形的某一部分新增新的顏色。

它屬於canvasGradient介面,所有漸變型別都使用它來在Canvas元素上圖形的特定位置提供顏色輸入。

語法

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

canvasGradient.addColorStop(offset_value, color);

引數

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

序號 引數及描述
1

offset_value

它取值為'0'到'1'(包含'0'和'1'),表示顏色停止點的位置。'0'表示漸變的起點,'1'表示終點。

2

color

使用指定的offset_value應用的顏色。

返回值

它將漸變色應用到Canvas元素上繪製的圖形上,並將結果直接渲染到畫布上。

示例1

以下示例使用HTML Canvas addColorStop()方法在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="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var grad = context.createLinearGradient(0, 0, 200, 100);
      context.fillStyle = grad;
      grad.addColorStop(0.3, 'blue');
      grad.addColorStop(0.5, 'grey');
      grad.addColorStop(0.7, 'purple');
      context.fillRect(30, 10, 190, 80);
   </script>
</body>
</html>

輸出

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

HTML Canvas AddColorStop Method

示例2

以下程式在Canvas元素上繪製一個矩形,並使用addColorStop()方法應用顏色圖案。

<!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="100" style="border: 1px solid black;"></canvas>
   <script>
      var canvas = document.getElementById('canvas');
      var context = canvas.getContext('2d');
      var grad = context.createLinearGradient(0, 0, 200, 100);
      context.fillStyle = grad;
      grad.addColorStop(0.25, 'purple');
      grad.addColorStop(0.90, 'cyan');
      context.fillRect(30, 10, 190, 80);
   </script>
</body>
</html>

輸出

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

HTML Canvas AddColorStop Method
html_canvas_colors_and_styles.htm
廣告
© . All rights reserved.