<polyline>
是SVG中用来绘制由多个直线段连接起来的折线的元素。与 <polygon>
类似,<polyline>
也是由多个点组成的,但不同的是,<polyline>
并不要求最后一个点与第一个点闭合,因此它适用于表示开放的多段线形状。
目录
基本语法
<polyline points="x1,y1 x2,y2 x3,y3 ..." fill="填充颜色" stroke="描边颜色" stroke-width="描边宽度" />
points
:定义折线的所有顶点,使用空格分隔每个坐标对。每个坐标对是x,y
格式,表示每个点的位置。fill
:填充颜色(如果适用)。对于折线通常不使用填充颜色。stroke
:折线的边框颜色。stroke-width
:折线的边框宽度,单位为像素。
属性详解
points
:- 该属性定义了折线的各个顶点,多个顶点之间使用空格分隔。每个顶点的坐标用
x,y
格式表示。 - 这些点将按顺序连接成一条折线。
<polyline>
只会绘制一条连续的折线段,而不会自动闭合。
- 该属性定义了折线的各个顶点,多个顶点之间使用空格分隔。每个顶点的坐标用
fill
:- 用于设置折线的填充颜色。对于折线来说,通常不需要使用填充颜色,除非是绘制封闭形状的折线(例如带有路径或连接的区域)。
stroke
:- 用于设置折线的边框颜色。可以使用颜色名称、十六进制颜色值或RGB格式。
stroke-width
:- 控制折线的边框宽度,单位为像素。默认宽度为
1
像素。
- 控制折线的边框宽度,单位为像素。默认宽度为
示例代码
- 简单折线
<svg width="200" height="200">
<polyline points="20,20 50,50 80,20 110,50" fill="none" stroke="blue" stroke-width="2" />
</svg>
- 这个例子绘制了一条简单的折线,四个顶点的坐标为(20,20)、(50,50)、(80,20)、(110,50),没有填充颜色,边框为蓝色,宽度为2像素。
- 折线与曲线组合
<svg width="200" height="200">
<polyline points="20,150 50,120 80,150 110,120" fill="none" stroke="red" stroke-width="3" />
</svg>
- 这个例子绘制了一条四个顶点的折线,坐标为(20,150)、(50,120)、(80,150)、(110,120),边框为红色,宽度为3像素。
- 带渐变的折线
<svg width="200" height="200">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<polyline points="20,20 50,80 80,20 110,80" fill="none" stroke="url(#grad1)" stroke-width="4" />
</svg>
- 这个例子绘制了一条折线,使用了从黄色到红色的线性渐变作为边框颜色,边框宽度为4像素。
- 动态折线
<svg width="200" height="200">
<polyline id="animatePolyline" points="20,100 50,50 80,100 110,50" fill="none" stroke="green" stroke-width="2" />
<animate
xlink:href="#animatePolyline"
attributeName="points"
from="20,100 50,50 80,100 110,50"
to="20,100 50,150 80,100 110,150"
dur="2s"
repeatCount="indefinite"
/>
</svg>
- 这个例子展示了一条动态折线,
points
属性在2秒内从原始位置平滑过渡到新的位置,动画循环进行。
- 交互式折线
<svg width="200" height="200">
<polyline id="hoverPolyline" points="20,100 50,50 80,100 110,50" fill="none" stroke="black" stroke-width="2" />
<script>
document.getElementById('hoverPolyline').addEventListener('mouseover', function() {
this.setAttribute('stroke', 'orange');
});
document.getElementById('hoverPolyline').addEventListener('mouseout', function() {
this.setAttribute('stroke', 'black');
});
</script>
</svg>
- 这个例子展示了一个交互式的折线,当鼠标悬停时,折线的颜色会变为橙色,移开时恢复为黑色。
参考资料
出站链接
<polyline>
元素是SVG图形中绘制折线的基础元素,能够用于创建多个不连接的线段或折线。它不仅能绘制简单的折线,还可以与渐变、动画、交互等结合,创造出更加丰富的图形效果。
发表回复