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

浏览器兼容性

另见