strokeStyle 描边颜色

strokeStyle属性用于设置Canvas图形的描边颜色。

基本语法

ctx.strokeStyle = color

颜色值类型

Canvas支持多种颜色格式:

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

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

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

// 颜色名称
ctx.strokeStyle = 'red'
ctx.strokeStyle = 'crimson'

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

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

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

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

基本用法

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

// 设置描边颜色
ctx.strokeStyle = '#e74c3c'
ctx.lineWidth = 3

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

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

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

描边颜色演示

不同描边颜色

渐变描边

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

ctx.strokeStyle = gradient
ctx.lineWidth = 5
ctx.strokeRect(50, 50, 100, 80)

// 径向渐变描边
const radialGradient = ctx.createRadialGradient(100, 100, 0, 100, 100, 50)
radialGradient.addColorStop(0, '#ffffff')
radialGradient.addColorStop(1, '#e74c3c')

ctx.strokeStyle = radialGradient
ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI * 2)
ctx.stroke()

渐变描边演示

渐变描边

填充与描边组合

// 先填充后描边
ctx.fillStyle = '#3498db'
ctx.strokeStyle = '#2980b9'
ctx.lineWidth = 3

ctx.beginPath()
ctx.arc(100, 100, 50, 0, Math.PI * 2)
ctx.fill()
ctx.stroke()

// 先描边后填充
ctx.strokeStyle = '#e74c3c'
ctx.fillStyle = '#c0392b'
ctx.lineWidth = 3

ctx.beginPath()
ctx.arc(250, 100, 50, 0, Math.PI * 2)
ctx.stroke()
ctx.fill()

填充与描边组合演示

填充与描边组合

注意事项

strokeStyle影响所有后续描边操作

ctx.strokeStyle = '#ff0000'
ctx.strokeRect(0, 0, 50, 50)  // 红色

ctx.strokeStyle = '#00ff00'
ctx.strokeRect(50, 0, 50, 50) // 绿色

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

lineWidth影响描边效果

ctx.lineWidth = 1
ctx.strokeStyle = '#e74c3c'
ctx.strokeRect(50, 50, 100, 100)

ctx.lineWidth = 5
ctx.strokeStyle = '#3498db'
ctx.strokeRect(200, 50, 100, 100)

ctx.lineWidth = 10
ctx.strokeStyle = '#2ecc71'
ctx.strokeRect(350, 50, 100, 100)

描边位置

// 描边以路径为中心,一半在内一半在外
ctx.lineWidth = 10
ctx.strokeStyle = '#e74c3c'
ctx.strokeRect(50, 50, 100, 100)
// 实际占用空间是 45-155 (50-5 到 150+5)

不同线宽演示

不同线宽的描边效果