<line> 是SVG中用来绘制直线的元素。通过设置起点和终点的坐标,可以绘制出任意方向的直线。<line> 元素支持多个属性来定制直线的样式,如颜色、宽度等。

目录

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

基本语法

<line x1="起点X" y1="起点Y" x2="终点X" y2="终点Y" stroke="描边颜色" stroke-width="描边宽度" />

  • x1:直线起点的X坐标。
  • y1:直线起点的Y坐标。
  • x2:直线终点的X坐标。
  • y2:直线终点的Y坐标。
  • stroke:直线的边框颜色。
  • stroke-width:直线的边框宽度,单位为像素。

属性详解

  • x1 和 y1
    • 控制直线的起点坐标。默认值为0,表示从坐标系的原点开始。
  • x2 和 y2
    • 控制直线的终点坐标。
  • stroke
    • 用于设置直线的颜色。可以使用颜色名称(如red),十六进制颜色值(如#ff0000),RGB(如rgb(255,0,0))等格式。
  • stroke-width
    • 控制直线的宽度,单位为像素。如果没有设置,默认值为1像素。

示例代码

  1. 基本直线
<svg width="200" height="200">
  <line x1="20" y1="20" x2="180" y2="20" stroke="blue" stroke-width="2" />
</svg>

  • 这个例子绘制了一条从(20, 20)到(180, 20)的蓝色直线,边框宽度为2像素。
  1. 不同颜色的直线
<svg width="200" height="200">
  <line x1="20" y1="50" x2="180" y2="50" stroke="green" stroke-width="4" />
  <line x1="20" y1="80" x2="180" y2="80" stroke="red" stroke-width="4" />
</svg>

  • 这个例子绘制了两条直线,分别是绿色和红色,宽度为4像素。
  1. 虚线直线
<svg width="200" height="200">
  <line x1="20" y1="100" x2="180" y2="100" stroke="black" stroke-width="2" stroke-dasharray="5,5" />
</svg>

  • 这个例子绘制了一条黑色的虚线,虚线长度为5像素,间隔为5像素。
  1. 动态直线
<svg width="200" height="200">
  <line id="animateLine" x1="20" y1="150" x2="180" y2="150" stroke="blue" stroke-width="2" />
  <animate
    xlink:href="#animateLine"
    attributeName="x2"
    from="20"
    to="180"
    dur="2s"
    repeatCount="indefinite"
  />
</svg>

  • 这个例子展示了一条动态的蓝色直线,x2属性在2秒内从20变化到180,动画循环进行。
  1. 交互式直线
<svg width="200" height="200">
  <line id="hoverLine" x1="20" y1="180" x2="180" y2="180" stroke="black" stroke-width="2" />
  <script>
    document.getElementById('hoverLine').addEventListener('mouseover', function() {
      this.setAttribute('stroke', 'orange');
    });
    document.getElementById('hoverLine').addEventListener('mouseout', function() {
      this.setAttribute('stroke', 'black');
    });
  </script>
</svg>

  • 这个例子展示了一个交互式的黑色直线,当鼠标悬停时,直线颜色变为橙色。

参考资料

出站链接

<line>元素是SVG图形中绘制直线的基础元素,适用于各种图形设计需求。它不仅能够绘制简单的直线,还可以与其他SVG元素和动画结合,创建动态效果、交互式元素以及复杂的图形。