<polygon> 是SVG中用来绘制多边形的元素。通过定义多个点坐标,<polygon> 可以绘制任意形状的多边形。它的形状是由多个直线段连接起来的,最终形成封闭的图形。与 <path> 不同,<polygon> 需要明确指定所有的顶点坐标。

目录

  1. 基本语法
  2. 属性详解
  3. 示例代码
  4. 参考资料
  5. 出站链接

基本语法

<polygon points="x1,y1 x2,y2 x3,y3 ..." fill="填充颜色" stroke="描边颜色" stroke-width="描边宽度" />

  • points:定义多边形的所有顶点,使用空格分隔每个坐标对。每个坐标对是x,y格式,表示每个顶点的位置。
  • fill:多边形的填充颜色。
  • stroke:多边形的边框颜色。
  • stroke-width:多边形的边框宽度,单位为像素。

属性详解

  • points
    • 该属性定义了多边形的各个顶点,多个顶点之间使用空格分隔。每个顶点的坐标用x,y格式表示。
  • fill
    • 用于设置多边形的填充颜色。可以使用颜色名称(如red)、十六进制颜色值(如#ff0000)或RGB格式(如rgb(255,0,0))等。
  • stroke
    • 用于设置多边形边框的颜色。支持与fill相同的颜色格式。
  • stroke-width
    • 控制多边形边框的宽度,单位为像素。如果没有设置,默认值为1像素。

示例代码

  1. 简单三角形
<svg width="200" height="200">
  <polygon points="50,150 100,50 150,150" fill="blue" stroke="black" stroke-width="2" />
</svg>

  • 这个例子绘制了一个三角形,三个顶点的坐标分别为(50,150),(100,50)和(150,150),填充颜色为蓝色,边框为黑色,边框宽度为2像素。
  1. 五边形
<svg width="200" height="200">
  <polygon points="100,30 150,60 130,120 70,120 50,60" fill="green" stroke="black" stroke-width="2" />
</svg>

  • 这个例子绘制了一个五边形,五个顶点的坐标分别为(100,30),(150,60),(130,120),(70,120)和(50,60),填充颜色为绿色,边框为黑色,边框宽度为2像素。
  1. 复杂多边形
<svg width="300" height="300">
  <polygon points="50,150 75,100 125,100 150,150 125,200 75,200" fill="yellow" stroke="red" stroke-width="3" />
</svg>

  • 这个例子绘制了一个六边形,六个顶点的坐标分别为(50,150),(75,100),(125,100),(150,150),(125,200),(75,200),填充颜色为黄色,边框为红色,边框宽度为3像素。
  1. 带渐变的多边形
<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>
  <polygon points="50,150 100,50 150,150" fill="url(#grad1)" stroke="black" stroke-width="2" />
</svg>

  • 这个例子绘制了一个三角形,填充了从黄色到红色的线性渐变,边框为黑色,边框宽度为2像素。
  1. 动态变化的多边形
<svg width="200" height="200">
  <polygon id="animatePolygon" points="50,150 100,50 150,150" fill="blue" stroke="black" stroke-width="2" />
  <animate
    xlink:href="#animatePolygon"
    attributeName="points"
    from="50,150 100,50 150,150"
    to="50,150 100,30 150,150"
    dur="2s"
    repeatCount="indefinite"
  />
</svg>

  • 这个例子展示了一个动态变化的三角形,points属性在2秒内从一个位置平滑过渡到另一个位置,动画循环进行。
  1. 交互式多边形
<svg width="200" height="200">
  <polygon id="hoverPolygon" points="50,150 100,50 150,150" fill="blue" stroke="black" stroke-width="2" />
  <script>
    document.getElementById('hoverPolygon').addEventListener('mouseover', function() {
      this.setAttribute('fill', 'green');
    });
    document.getElementById('hoverPolygon').addEventListener('mouseout', function() {
      this.setAttribute('fill', 'blue');
    });
  </script>
</svg>

  • 这个例子展示了一个交互式的蓝色三角形,当鼠标悬停时,颜色变为绿色,移开时恢复为蓝色。

参考资料

出站链接

<polygon> 元素是SVG图形中绘制多边形的基础元素,能够灵活地创建任意形状的封闭图形。它可以与填充颜色、边框样式、渐变、动画等相结合,创建出丰富的图形效果,广泛应用于网页设计、图标制作以及互动式应用中。