CanvasRenderingContext2D:createConicGradient() 方法

Baseline 2023
Newly available

Since April 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

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");

// 创建一个锥形渐变
// 开始角度为 0
// 中心位置为 100, 100
const gradient = ctx.createConicGradient(0, 100, 100);

// 添加五个色标
gradient.addColorStop(0, "red");
gradient.addColorStop(0.25, "orange");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(0.75, "green");
gradient.addColorStop(1, "blue");

// 设置填充样式并绘制矩形
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 200);

矩形结果

规范

Specification
HTML
# dom-context-2d-createconicgradient-dev

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
createConicGradient

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

参见