CanvasRenderingContext2D:createConicGradient() 方法

Baseline 已广泛支持

此功能已成熟,并且在许多设备和浏览器版本中都能正常工作。自 ⁨2023 年 4 月⁩ 起,所有浏览器均已支持此功能。

Canvas 2D API 的 CanvasRenderingContext2D.createConicGradient() 方法创建一个围绕给定坐标点的渐变。

此方法返回一个圆锥 CanvasGradient。要将其应用于形状,必须先将渐变赋值给 fillStylestrokeStyle 属性。

注意: 渐变坐标是全局的,即相对于当前坐标空间。当应用于形状时,坐标相对于形状的坐标。

语法

js
createConicGradient(startAngle, x, y)

参数

startAngle

渐变开始的角度,以弧度为单位。角度从从中心点向右水平延伸的线开始,并顺时针进行。

x

渐变中心的 x 轴坐标。

y

渐变中心的 y 轴坐标。

返回值

CanvasGradient

一个圆锥 CanvasGradient

示例

用圆锥渐变填充矩形

此示例使用 createConicGradient() 方法初始化一个圆锥渐变。然后在中心坐标周围创建五个颜色停止点。最后,将渐变赋值给画布上下文,并渲染为一个填充矩形。

HTML

html
<canvas id="canvas" width="240" height="240"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Create a conic gradient
// The start angle is 0
// The center position is 100, 100
const gradient = ctx.createConicGradient(0, 100, 100);

// Add five color stops
gradient.addColorStop(0, "red");
gradient.addColorStop(0.25, "orange");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(0.75, "green");
gradient.addColorStop(1, "blue");

// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 200);

矩形结果

规范

规范
HTML
# dom-context-2d-createconicgradient-dev

浏览器兼容性

另见