Canvas API
CanvasGradient.addColorStop() 方法为给定的 canvas 渐变添加一个由偏移值(offset)和颜色值(color)指定的色标。
语法
addColorStop(offset, color)
参数
offset- : 一个在
0到1之间(包含边界)的数字,表示色标的位置。0表示渐变的起始位置,1表示渐变的结束位置。
- : 一个在
color- : 一个 CSS <color> 值,表示色标的颜色。
返回值
无(undefined)。
异常
IndexSizeErrorDOMException- : 如果
offset不在 0 和 1 之间(包括边界),则抛出此异常。
- : 如果
SyntaxErrorDOMException- : 如果
color无法解析为 CSS <color> 值,则抛出此异常。
- : 如果
示例
向渐变中添加色标
此示例使用 addColorStop 方法向线性 CanvasGradient 对象中添加色标。然后使用该渐变填充矩形。
HTML
<canvas id="canvas"></canvas>
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(0.7, "white");
gradient.addColorStop(1, "pink");
ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);
结果
向渐变中添加色标
规范
浏览器兼容性
参见
- 接口定义 CanvasGradient
- CanvasRenderingContext2D.createLinearGradient()
- CanvasRenderingContext2D.createRadialGradient()
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
