lineWidth属性控制绘制线条的粗细,默认值为1像素。
ctx.lineWidth = value
参数value为正数,表示线条宽度(单位:像素)。
当线宽为奇数时,线条会向两侧各延伸半个像素,可能导致模糊。
// 奇数宽度 - 可能模糊
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(50.5, 50) // 使用.5偏移
ctx.lineTo(200.5, 50)
ctx.stroke()
// 偶数宽度 - 清晰
ctx.lineWidth = 2
ctx.beginPath()
ctx.moveTo(50, 100)
ctx.lineTo(200, 100)
ctx.stroke()
lineWidth影响所有描边操作,包括矩形、圆形、路径等。
// 描边矩形
ctx.lineWidth = 5
ctx.strokeRect(50, 50, 100, 80)
// 描边圆形
ctx.lineWidth = 8
ctx.beginPath()
ctx.arc(250, 90, 40, 0, Math.PI * 2)
ctx.stroke()
线宽居中分布
线条以坐标为中心向两侧延伸,宽度为10的线条实际占据20像素区域。
最小有效值
线宽最小值为正数,0或负值会被忽略。
性能影响
过大的线宽会增加渲染开销,尤其在复杂路径上。