xDocxDoc
AI
前端
后端
iOS
Android
Flutter
AI
前端
后端
iOS
Android
Flutter
  • SVG

SVG

核心概念

SVG(可缩放矢量图形)是一种基于XML的矢量图像格式,不同于JPEG/GIF等位图格式。其核心特性包括:

  • 🧩 由几何指令而非像素组成,支持无损缩放
  • ⚡ 可直接嵌入HTML文档操作(内联SVG)
  • 🎨 可通过CSS/JavaScript动态修改属性
  • 📐 提供专属绘图元素如 <circle>, <rect>, <path>

内联SVG示例

<div class="wrapper">
  <svg width="100" height="100">
    <!-- 绘制圆心(50,50) 半径30的粉色圆形 -->
    <circle fill="hotpink" r="30" cx="50" cy="50" />
  </svg>
</div>

CSS控制SVG动画

<style>
  circle {
    fill: hotpink;      /* 填充色 */
    transition: r 400ms, cy 600ms;  /* 半径/Y坐标的过渡动画 */
  }
  button:hover circle {
    r: 50px;    /* 悬停时半径变为50px */
    cy: 100px;  /* 圆心下移 */
  }
</style>

<button>
  <svg width="100" height="100">
    <circle r="30" cx="50" cy="50" />
  </svg>
</button>

基础图形元素

1. 直线 <line>

<!-- 从(80,80)到(200,200)的橙色直线 -->
<line 
  x1="80" y1="80"    <!-- 起点坐标 -->
  x2="200" y2="200"  <!-- 终点坐标 -->
  stroke="orange"    <!-- 描边颜色 -->
  stroke-width="5"   <!-- 描边宽度 -->
/>

2. 矩形 <rect>

<!-- 左上角(60,100) 宽180高100的矩形 -->
<rect 
  x="60" y="100" 
  width="180" height="100"
  rx="20" ry="10"     <!-- X/Y轴圆角半径 -->
  stroke="blue" 
/>

⚠️ 当宽/高为0时图形不渲染(退化图形)

3. 圆形 <circle>

<!-- 圆心(140,140) 半径70 -->
<circle cx="140" cy="140" r="70" fill="green" />

4. 椭圆 <ellipse>

<!-- 圆心(150,150) 横轴半径75 纵轴半径50 -->
<ellipse cx="150" cy="150" rx="75" ry="50" fill="purple" />

5. 多边形 <polygon>

<!-- 依次连接各点形成封闭图形 -->
<polygon 
  points="60,100 100,180 140,140 180,180 220,100" 
  fill="teal"
/>

关键机制:viewBox坐标系

<svg width="300" height="300" viewBox="0 0 300 300">
  <!-- 
    viewBox="minX minY width height" 
    建立内部坐标系,实现响应式缩放
  -->
  <rect x="0" y="0" width="200" height="200" />
</svg>

描边(stroke)高级控制

核心属性

circle {
  stroke: gold;               /* 描边颜色 */
  stroke-width: 6px;           /* 描边粗细 */
  stroke-dasharray: 20, 14;    /* 实线/间隙长度 */
  stroke-linecap: round;       /* 端点样式(round/square/butt) */
  stroke-dashoffset: 0;        /* 虚线偏移量 */
}

动画实现技巧

路径绘制动画

<script>
// 计算路径总长
const path = document.querySelector('path');
const length = path.getTotalLength(); 

// 设置初始状态
path.style.strokeDasharray = `${length} ${length + 100}`;
path.style.strokeDashoffset = length;

// 执行动画
path.style.transition = "stroke-dashoffset 2s";
path.style.strokeDashoffset = "0";
</script>

旋转加载动画

@keyframes spin {
  to { stroke-dashoffset: -100; } /* 负值实现连续旋转 */
}

.spinner {
  stroke-dasharray: 30, 150;
  animation: spin 1s linear infinite;
}

总结

💡 核心要点总结

  1. 矢量优势
    SVG通过数学指令渲染图形,支持无限缩放不失真

  2. DOM集成
    内联SVG可直接用CSS/JS操作,实现动态效果

  3. 坐标系系统
    viewBox建立独立坐标系解决响应式适配问题

  4. 描边动画
    结合stroke-dasharray和stroke-dashoffset实现绘制效果

  5. 进阶路径
    <path>元素(本文未展开)支持贝塞尔曲线等复杂图形

最后更新: 2025/8/26 10:07