径向渐变是一种从中心点向外辐射的颜色过渡效果。
const gradient = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1)
gradient.addColorStop(offset, color)
| 参数 | 类型 | 说明 |
|---|---|---|
| x0, y0 | number | 内圆中心坐标 |
| r0 | number | 内圆半径 |
| x1, y1 | number | 外圆中心坐标 |
| r1 | number | 外圆半径 |
| offset | number | 颜色停止点位置(0-1) |
| color | string | 颜色值 |
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
// 创建径向渐变
const gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 100)
gradient.addColorStop(0, '#ffffff')
gradient.addColorStop(0.5, '#3498db')
gradient.addColorStop(1, '#2980b9')
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(100, 100, 100, 0, Math.PI * 2)
ctx.fill()
// 内圆半径不为0,创建环形效果
const gradient = ctx.createRadialGradient(100, 100, 30, 100, 100, 100)
gradient.addColorStop(0, 'transparent')
gradient.addColorStop(0.3, '#3498db')
gradient.addColorStop(1, '#2980b9')
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(100, 100, 100, 0, Math.PI * 2)
ctx.fill()
// 内外圆中心不同,创建偏心效果
const gradient = ctx.createRadialGradient(80, 80, 0, 100, 100, 100)
gradient.addColorStop(0, '#ffffff')
gradient.addColorStop(0.5, '#3498db')
gradient.addColorStop(1, '#2980b9')
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(100, 100, 100, 0, Math.PI * 2)
ctx.fill()
function drawSphere(ctx, x, y, radius, lightColor, darkColor) {
const gradient = ctx.createRadialGradient(
x - radius * 0.3, y - radius * 0.3, 0,
x, y, radius
)
gradient.addColorStop(0, '#ffffff')
gradient.addColorStop(0.2, lightColor)
gradient.addColorStop(0.8, darkColor)
gradient.addColorStop(1, '#1a1a1a')
ctx.fillStyle = gradient
ctx.beginPath()
ctx.arc(x, y, radius, 0, Math.PI * 2)
ctx.fill()
}
drawSphere(ctx, 100, 100, 50, '#3498db', '#2980b9')
drawSphere(ctx, 200, 100, 50, '#e74c3c', '#c0392b')
drawSphere(ctx, 300, 100, 50, '#2ecc71', '#27ae60')
// 创建聚光灯效果
const gradient = ctx.createRadialGradient(200, 100, 0, 200, 100, 150)
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.8)')
gradient.addColorStop(0.3, 'rgba(255, 255, 255, 0.3)')
gradient.addColorStop(1, 'rgba(255, 255, 255, 0)')
ctx.fillStyle = gradient
ctx.fillRect(0, 0, 400, 200)
半径必须为正数
// 正确
const gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 100)
// 错误:半径不能为负数
const gradient = ctx.createRadialGradient(100, 100, -10, 100, 100, 100)
内圆半径大于外圆
// 内圆半径大于外圆半径时,渐变方向反转
const gradient = ctx.createRadialGradient(100, 100, 100, 100, 100, 0)
// 渐变从外向内
颜色停止点范围
// 颜色停止点必须在0-1之间
const gradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 100)
gradient.addColorStop(0, '#ffffff')
gradient.addColorStop(0.5, '#3498db')
gradient.addColorStop(1, '#2980b9')
渐变区域
// 渐变只在内外圆之间有效
const gradient = ctx.createRadialGradient(100, 100, 20, 100, 100, 80)
// 内圆内部使用第一个颜色停止点的颜色
// 外圆外部使用最后一个颜色停止点的颜色