fillStyle 填充颜色

fillStyle属性用于设置Canvas图形的填充颜色。

基本语法

ctx.fillStyle = color

颜色值类型

Canvas支持多种颜色格式:

// 十六进制颜色
ctx.fillStyle = '#ff0000'
ctx.fillStyle = '#f00'

// RGB颜色
ctx.fillStyle = 'rgb(255, 0, 0)'

// RGBA颜色
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'

// 颜色名称
ctx.fillStyle = 'red'
ctx.fillStyle = 'tomato'

// HSL颜色
ctx.fillStyle = 'hsl(0, 100%, 50%)'

// HSLA颜色
ctx.fillStyle = 'hsla(0, 100%, 50%, 0.5)'

// 渐变对象
const gradient = ctx.createLinearGradient(0, 0, 200, 0)
gradient.addColorStop(0, '#ff0000')
gradient.addColorStop(1, '#0000ff')
ctx.fillStyle = gradient

// 图案对象
const pattern = ctx.createPattern(image, 'repeat')
ctx.fillStyle = pattern

基本用法

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

// 设置填充颜色
ctx.fillStyle = '#3498db'

// 绘制矩形
ctx.fillRect(50, 50, 100, 80)

// 绘制圆形
ctx.beginPath()
ctx.arc(200, 90, 40, 0, Math.PI * 2)
ctx.fill()

// 绘制三角形
ctx.beginPath()
ctx.moveTo(300, 50)
ctx.lineTo(350, 130)
ctx.lineTo(250, 130)
ctx.closePath()
ctx.fill()

填充颜色演示

不同填充颜色

渐变填充

// 线性渐变
const linearGradient = ctx.createLinearGradient(0, 0, 200, 0)
linearGradient.addColorStop(0, '#3498db')
linearGradient.addColorStop(0.5, '#9b59b6')
linearGradient.addColorStop(1, '#e74c3c')

ctx.fillStyle = linearGradient
ctx.fillRect(0, 0, 200, 100)

// 径向渐变
const radialGradient = ctx.createRadialGradient(100, 150, 0, 100, 150, 100)
radialGradient.addColorStop(0, '#ffffff')
radialGradient.addColorStop(0.3, '#3498db')
radialGradient.addColorStop(1, '#2980b9')

ctx.fillStyle = radialGradient
ctx.fillRect(0, 100, 200, 100)

渐变填充演示

渐变填充

图案填充

// 创建图案
const patternCanvas = document.createElement('canvas')
patternCanvas.width = 20
patternCanvas.height = 20
const patternCtx = patternCanvas.getContext('2d')

patternCtx.fillStyle = '#3498db'
patternCtx.fillRect(0, 0, 10, 10)
patternCtx.fillRect(10, 10, 10, 10)

const pattern = ctx.createPattern(patternCanvas, 'repeat')
ctx.fillStyle = pattern
ctx.fillRect(0, 0, 200, 200)

图案填充演示

图案填充

注意事项

fillStyle影响所有后续填充操作

ctx.fillStyle = '#ff0000'
ctx.fillRect(0, 0, 50, 50)  // 红色

ctx.fillStyle = '#00ff00'
ctx.fillRect(50, 0, 50, 50) // 绿色

ctx.fillRect(100, 0, 50, 50) // 仍然是绿色

颜色值有效性

// 无效颜色值会被忽略
ctx.fillStyle = 'invalid-color'
ctx.fillRect(0, 0, 50, 50) // 不会绘制

// 使用try-catch处理
try {
  ctx.fillStyle = someColorValue
  ctx.fillRect(0, 0, 50, 50)
} catch (e) {
  console.error('颜色设置失败:', e)
}

性能考虑

// 避免频繁设置相同的颜色
for (let i = 0; i < 100; i++) {
  ctx.fillStyle = '#ff0000' // 每次都设置
  ctx.fillRect(i * 10, 0, 10, 10)
}

// 更好的方式
ctx.fillStyle = '#ff0000' // 只设置一次
for (let i = 0; i < 100; i++) {
  ctx.fillRect(i * 10, 0, 10, 10)
}