线条样式

线条样式控制绘制路径的外观,包括宽度、端点形状、连接方式等属性。

线条属性概览

属性类型说明
lineWidthnumber线条宽度
lineCapstring线条端点样式
lineJoinstring线条连接样式
miterLimitnumber斜接限制
lineDashOffsetnumber虚线偏移
setLineDash()method设置虚线模式
getLineDash()method获取虚线模式

设置线条宽度

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

ctx.strokeStyle = '#3498db'

ctx.lineWidth = 1
ctx.strokeRect(50, 50, 80, 60)

ctx.lineWidth = 5
ctx.strokeRect(150, 50, 80, 60)

ctx.lineWidth = 10
ctx.strokeRect(250, 50, 80, 60)

线条宽度演示

不同线条宽度

线条端点样式

lineCap属性控制线条端点的形状:

说明
butt平直端点(默认)
round圆形端点
square方形端点
ctx.lineWidth = 15

ctx.lineCap = 'butt'
ctx.beginPath()
ctx.moveTo(50, 50)
ctx.lineTo(200, 50)
ctx.stroke()

ctx.lineCap = 'round'
ctx.beginPath()
ctx.moveTo(50, 100)
ctx.lineTo(200, 100)
ctx.stroke()

ctx.lineCap = 'square'
ctx.beginPath()
ctx.moveTo(50, 150)
ctx.lineTo(200, 150)
ctx.stroke()

端点样式演示

线条端点样式

线条连接样式

lineJoin属性控制两条线段连接处的形状:

说明
miter尖角连接(默认)
round圆角连接
bevel斜角连接
ctx.lineWidth = 15

ctx.lineJoin = 'miter'
ctx.beginPath()
ctx.moveTo(50, 150)
ctx.lineTo(100, 50)
ctx.lineTo(150, 150)
ctx.stroke()

ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(200, 150)
ctx.lineTo(250, 50)
ctx.lineTo(300, 150)
ctx.stroke()

ctx.lineJoin = 'bevel'
ctx.beginPath()
ctx.moveTo(350, 150)
ctx.lineTo(400, 50)
ctx.lineTo(450, 150)
ctx.stroke()

连接样式演示

线条连接样式

斜接限制

当lineJoin为miter时,miterLimit控制尖角的最大长度:

ctx.lineWidth = 10
ctx.lineJoin = 'miter'

// 小角度会产生很长的尖角
ctx.miterLimit = 10
ctx.beginPath()
ctx.moveTo(50, 100)
ctx.lineTo(100, 50)
ctx.lineTo(150, 100)
ctx.stroke()

// 限制尖角长度
ctx.miterLimit = 2
ctx.beginPath()
ctx.moveTo(200, 100)
ctx.lineTo(250, 50)
ctx.lineTo(300, 100)
ctx.stroke()

斜接限制演示

斜接限制效果

虚线样式

使用setLineDash方法创建虚线效果:

// 实线
ctx.setLineDash([])
ctx.strokeRect(50, 50, 100, 60)

// 虚线 [线段长度, 间隙长度]
ctx.setLineDash([10, 5])
ctx.strokeRect(180, 50, 100, 60)

// 点划线
ctx.setLineDash([20, 5, 5, 5])
ctx.strokeRect(50, 150, 100, 60)

// 复杂虚线
ctx.setLineDash([15, 3, 3, 3, 3, 3])
ctx.strokeRect(180, 150, 100, 60)

虚线样式演示

虚线样式

虚线偏移动画

lineDashOffset属性可以创建动画效果:

let offset = 0

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  
  ctx.setLineDash([10, 5])
  ctx.lineDashOffset = -offset
  
  ctx.strokeRect(50, 50, 200, 100)
  
  offset++
  if (offset > 15) offset = 0
  
  requestAnimationFrame(animate)
}

虚线动画演示

虚线动画效果

综合示例

线条样式综合应用

注意事项

线条宽度与坐标

// 线条以坐标为中心向两侧扩展
ctx.lineWidth = 10
ctx.beginPath()
ctx.moveTo(50, 100)
ctx.lineTo(200, 100)
ctx.stroke()
// 线条实际占据 y=95 到 y=105

奇数宽度的像素对齐

// 奇数宽度需要偏移0.5像素才能清晰
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(50.5, 50)
ctx.lineTo(200.5, 50)
ctx.stroke()

虚线重置

// 绘制虚线后需要重置
ctx.setLineDash([10, 5])
ctx.strokeRect(50, 50, 100, 80)

// 重置为实线
ctx.setLineDash([])
ctx.strokeRect(180, 50, 100, 80)