CanvasRenderingContext2D:createLinearGradient() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

The gradient transitions colors along the gradient line, starting at point x0, y0 and going to x1, y1, even if those points extend the gradient line beyond the edges of the element on which the gradient is drawn.

此方法返回一個線性 CanvasGradient。要將其應用於形狀,必須首先將漸變賦值給 fillStylestrokeStyle 屬性。

注意: 漸變座標是全域性的,即相對於當前座標空間。當應用於形狀時,座標相對於形狀的座標。

語法

js
createLinearGradient(x0, y0, x1, y1)

createLinearGradient() 方法由四個引數定義,用於指定漸變線的起點和終點。

引數

x0

起點的 x 軸座標。

y0

起點的 y 軸座標。

x1

終點的 x 軸座標。

y1

終點的 y 軸座標。

返回值

一個使用指定直線初始化的線性 CanvasGradient

異常

NotSupportedError DOMException

當作為引數傳遞了非有限值時丟擲。

示例

用線性漸變填充矩形

此示例使用 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

瀏覽器相容性

另見