径向渐变

径向渐变是一种从中心点向外辐射的颜色过渡效果。

方法语法

const gradient = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1)
gradient.addColorStop(offset, color)
参数类型说明
x0, y0number内圆中心坐标
r0number内圆半径
x1, y1number外圆中心坐标
r1number外圆半径
offsetnumber颜色停止点位置(0-1)
colorstring颜色值

基本用法

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

// 内圆半径不为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()

偏心渐变演示

偏心渐变效果(模拟光照)

创建3D球体效果

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')

3D球体演示

3D球体效果

聚光灯效果

// 创建聚光灯效果
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)
// 内圆内部使用第一个颜色停止点的颜色
// 外圆外部使用最后一个颜色停止点的颜色