CanvasRenderingContext2D:createLinearGradient() 方法
Canvas 2D API 的 CanvasRenderingContext2D.createLinearGradient() 方法會在連線兩個給定座標點的直線上建立一個漸變。

此方法返回一個線性 CanvasGradient。要將其應用於形狀,必須首先將漸變賦值給 fillStyle 或 strokeStyle 屬性。
注意: 漸變座標是全域性的,即相對於當前座標空間。當應用於形狀時,座標不相對於形狀的座標。
語法
js
createLinearGradient(x0, y0, x1, y1)
createLinearGradient() 方法由四個引數定義,用於指定漸變線的起點和終點。
引數
返回值
一個使用指定直線初始化的線性 CanvasGradient。
異常
NotSupportedErrorDOMException-
當作為引數傳遞了非有限值時丟擲。
示例
用線性漸變填充矩形
此示例使用 createLinearGradient() 方法初始化一個線性漸變。然後,在漸變的起點和終點之間建立三個顏色停止點。最後,將漸變賦值給 Canvas 上下文,並渲染為一個填充的矩形。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Create a linear gradient
// The start gradient point is at x=20, y=0
// The end gradient point is at x=220, y=0
const gradient = ctx.createLinearGradient(20, 0, 220, 0);
// Add three color stops
gradient.addColorStop(0, "green");
gradient.addColorStop(0.5, "cyan");
gradient.addColorStop(1, "green");
// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-createlineargradient-dev |
瀏覽器相容性
載入中…