详细介绍SVG折线polyline元素的绑制方法,包括points属性、填充规则等设置。通过实际案例掌握折线的各种用法,适合前端开发者学习SVG图形绑制。 折线是由多个点连接而成的开放路径。
<polyline>元素适合绑制折线图、趋势线、开放的多点连线等。
<polyline points="x1,y1 x2,y2 x3,y3 ..."/>
points:点坐标列表,用空格或逗号分隔<polyline points="20,130 70,80 120,100 170,50 220,70 270,30 320,60 370,20"
fill="none" stroke="#3498db" stroke-width="2"/>
points 属性支持多种格式:
<polyline points="20,100 60,60 100,80 140,40" fill="none" stroke="#3498db" stroke-width="2"/>
<polyline points="180 100 220 60 260 80 300 40" fill="none" stroke="#e74c3c" stroke-width="2"/>
<polyline points="20,80 80,20 140,60 200,30 260,70"
fill="none" stroke="#3498db" stroke-width="2"/>
<polyline points="20,80 80,20 140,60 200,30 260,70 260,80 20,80"
fill="#3498db" fill-opacity="0.3" stroke="#3498db" stroke-width="2"/>
<polyline points="20,80 80,20 140,60 200,30 260,70"
fill="#e74c3c" fill-opacity="0.3" stroke="#e74c3c" stroke-width="2"/>
注意:设置 fill 后,折线会自动闭合到起点形成填充区域。
<polyline points="50,160 100,120 150,140 200,80 250,100 300,60 350,90"
fill="none" stroke="#3498db" stroke-width="2"/>
<polyline points="50,140 100,150 150,100 200,120 250,70 300,90 350,50"
fill="none" stroke="#e74c3c" stroke-width="2"/>
<polyline points="50,130 100,90 150,110 200,60 250,80 300,40 350,70 350,130 50,130"
fill="#3498db" fill-opacity="0.3" stroke="#3498db" stroke-width="2"/>
<polyline points="100,10 70,60 90,60 60,100 85,100 40,140 120,80 95,80 130,50 100,50 140,10"
fill="#f39c12" stroke="#e67e22" stroke-width="2"/>
<polyline points="20,40 40,20 60,40 80,20 100,40 120,20 140,40 160,20 180,40 200,20 220,40 240,20 260,40 280,20"
fill="none" stroke="#9b59b6" stroke-width="2"/>
<polyline points="20,50 60,50 80,50 100,20 120,80 140,50 180,50 200,50 220,50 240,20 260,80 280,50 320,50 340,50 360,50 380,50"
fill="none" stroke="#e74c3c" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="20,80 60,20 100,80 140,20 180,80" fill="none" stroke="#3498db" stroke-width="8" stroke-linejoin="miter"/>
<polyline points="220,80 260,20 300,80 340,20 380,80" fill="none" stroke="#e74c3c" stroke-width="8" stroke-linejoin="round"/>
<polyline points="20,60 70,20 120,50 170,30 220,60 270,20"
fill="none" stroke="#3498db" stroke-width="2" stroke-dasharray="10,5"/>
| 特性 | polyline | polygon |
|---|---|---|
| 路径类型 | 开放路径 | 闭合路径 |
| 自动闭合 | 否 | 是 |
| 填充行为 | 可选 | 默认填充 |
| 适用场景 | 折线图、趋势线 | 多边形、封闭图形 |
Q: 折线不显示?
A: 检查以下几点:
stroke 属性points 格式是否正确Q: 折线有奇怪的填充?
A: 设置 fill="none" 或 fill="transparent":
<polyline points="..." fill="none" stroke="#333"/>
Q: 如何让折线更平滑?
A: 使用 <path> 元素的曲线命令,或者使用 CSS 属性:
polyline {
stroke-linejoin: round;
stroke-linecap: round;
}
Q: points 属性太长怎么办?
A: 可以用 JavaScript 动态生成:
const points = data.map(d => `${d.x},${d.y}`).join(' ');
polyline.setAttribute('points', points);
折线是连接多个点的开放路径,通过 points 属性定义所有点坐标。折线常用于折线图、趋势线等场景。注意设置 fill="none" 避免意外的填充效果。如果需要闭合的多边形,应该使用 <polygon> 元素。