线条样式控制绘制路径的外观,包括宽度、端点形状、连接方式等属性。
| 属性 | 类型 | 说明 |
|---|---|---|
| lineWidth | number | 线条宽度 |
| lineCap | string | 线条端点样式 |
| lineJoin | string | 线条连接样式 |
| miterLimit | number | 斜接限制 |
| lineDashOffset | number | 虚线偏移 |
| 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)