图片预览
封面预览:SVG 入门:从元素语法到自己画一个进度环

封面预览:SVG 入门:从元素语法到自己画一个进度环

SVG 入门:从元素语法到自己画一个进度环

·6 分钟阅读

一份 SVG 学习笔记:先过一遍 svg、circle、path 等元素的语法与 fill、stroke 样式,再说清 viewBox 的坐标换算,最后用 JavaScript 直接改属性,手写环形进度条与条形统计图两个小例子。

一、什么时候该用 SVG

位图(PNG、JPEG、WebP)记录每个像素的颜色,SVG 记录「形状怎么画」——一段文本,写着圆心在哪、半径多大。所以同一张图放大十倍,位图开始发糊,SVG 还是干净的,因为它按坐标重画。

它因此适合图标、logo、图表、地图,以及需要跟着主题变色、需要由程序生成或修改的图形。还有个常被忽略的好处:SVG 是文本,能被 CSS 改样式、被 JavaScript 改属性、被读屏软件读出来。

三种情况别用:照片和复杂插画,几千个路径节点的 SVG 往往比 JPEG 更大、渲染更慢;只需要一张永远不变的静态图,PNG 更省事;长列表里成百上千个内联 SVG,会实打实拖慢页面。

一个前提要记住:只有内联到 HTML 里,CSS 和 JavaScript 才够得着 SVG 内部。

<!-- 内联:它既是图形,也是一个 DOM 节点 -->
<svg width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="#41B883"></circle>
</svg>

写成单独文件再用标签引入,它就只是一个资源,里面的节点碰不到:

<img src="circle.svg" alt="圆形图标" />
<object data="circle.svg" type="image/svg+xml"></object>
<embed src="circle.svg" type="image/svg+xml" />
<iframe src="circle.svg"></iframe>

CSS 也能直接用它,还可以编码成 Data URL 塞进 HTML:

.logo {
  background: url(circle.svg);
}
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1MCIgZmlsbD0ib3JhbmdlIi8+PC9zdmc+" alt="内联的橙色圆形" />

二、最小可运行示例

存成 .html 打开就能跑,不需要任何构建工具。

<!DOCTYPE html>
<html lang="zh-CN">
  <body>
    <svg id="demo" width="240" height="120" viewBox="0 0 240 120">
      <circle cx="60" cy="60" r="40" fill="#41B883"></circle>
      <rect x="140" y="20" width="80" height="80" fill="#34495E"></rect>
    </svg>
    <button id="paint">换个颜色</button>
    <script>
      const svg = document.getElementById("demo");
      document.getElementById("paint").onclick = () => {
        svg.querySelector("rect").setAttribute("fill", "#E67E22");
      };
    </script>
  </body>
</html>

看到一个绿色圆形和一个深蓝色方块;点按钮,方块变橙。后面所有内容都是这三件事的展开:元素描述形状,属性给参数,JavaScript 改属性。 再进一步就是让它动起来——还是改属性,只是交给定时器反复改:

<div class="enlarge-svg">
  <svg width="500" height="500">
    <rect x="50" y="50" width="100" height="100" class="rect"></rect>
  </svg>
</div>
<button>放大并移动</button>
.enlarge-svg {
  width: 500px;
  border: 1px dashed saddlebrown;
}
document.querySelector("button").onclick = () => {
  const rect = document.querySelector("rect");
  rect.setAttribute("width", 200);
  rect.setAttribute("height", 200);
  rect.setAttribute("fill", "orange");
  rect.style.transition = "all 1s ease-in-out";
  let x = 20;
  setInterval(() => {
    x += 20;
    rect.setAttribute("x", x);
  }, 100);
};

三、先搞懂坐标系

<svg> 的 width、height 决定它在页面上占多大,两个都不写就是 300 × 150 像素。

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

viewBox 是另一层,四个值依次是 min-x min-y width height:先在内部坐标系里框出一块矩形,再把这矩形等比缩放、塞进画布。

<svg width="100" height="100" viewBox="50 50 50 50">
  <circle cx="50" cy="50" r="50" fill="orange" />
</svg>

半径 50、圆心 (50,50) 的圆本来占满 0~100。viewBox 只框出 (50,50) 到 (100,100),于是看到的是圆的右下四分之一;这块 50×50 的区域被撑满到 100×100 的画布,所以放大 2 倍(100 ÷ 50)。「看到四分之一圆」说的是取景范围,「放大 2 倍」说的是缩放比,两件事不能混。

只写 viewBox、不写宽高,SVG 会撑满父元素;比例不一致时默认 preserveAspectRatio="xMidYMid meet"——等比缩放、居中,不会拉伸。

一句话记法:viewBox 定义纸上画了多大一块,width/height 定义贴到屏幕上多大。

四、形状、样式、动画

日常用到的就下面这些,其余都是它们的变体:

元素 关键属性 画什么
circle cx cy r 圆
ellipse cx cy rx ry 椭圆
rect x y width height,rx 圆角 矩形
line x1 y1 x2 y2 线段
polyline points 折线,不闭合
polygon points 多边形,首尾自动相连
path d 任意路径
text x y 文本,从基线开始
use href,x y 是额外的平移量 复用已有节点
g 无 分组,可整体变换
defs 无 只定义、不渲染
pattern width height patternUnits 可平铺的图案
image href 嵌入位图

path 值得单独说,因为其他形状它都能画。d 里每个字母是一个动作:M 移到、L 直线、H、V 水平与垂直、C 三次贝塞尔、A 圆弧、Z 闭合。

<svg width="300" height="300">
  <path d="M 18,3 L 46,3 L 46,40 L 61,40 L 32,68 L 3,40 L 18,40 Z"></path>
</svg>

样式分两类,这决定了「为什么我的 CSS 不生效」:几何属性(cx、r、d、points)只能用属性或 JavaScript 改,CSS 碰不到;表现属性(fill、stroke、stroke-width、stroke-dasharray)两者都能设,而且 CSS 优先级更高——写在 <style> 里的规则会盖掉元素上的同名属性。文字颜色用 fill,不是 color。

同一个圆,用类名给它上色和描边:

transform 在 SVG 里可以直接带中心点:rotate(-90, 350, 350) 是绕 (350,350) 转 -90 度;CSS 的 rotate() 默认绕原点,得配 transform-origin 才等价。

动画有两条路:CSS 的 transition / animation 作用在表现属性上,最省事;SMIL(<animate>、<animateTransform>)把动画写进元素里,跟着文件走,但调试和框架支持都一般。

<svg width="600" height="600">
  <rect x="0" y="0" width="100" height="50" fill="orange">
    <animate attributeName="x" from="0" to="500" dur="2s" repeatCount="indefinite"></animate>
    <animate attributeName="y" from="0" to="450" dur="3s" repeatCount="indefinite"></animate>
  </rect>
</svg>

animateTransform 有个坑:from 和 to 里的旋转中心必须一致,否则图形边转边漂。from="0 50 25" 配 to="360 50 25" 才是原地打转——(50,25) 正是这个矩形的中心。

<svg width="600" height="600">
  <rect x="0" y="0" width="100" height="50" fill="blue">
    <animateTransform
      attributeName="transform"
      type="rotate"
      begin="0"
      dur="2s"
      from="0 50 25"
      to="360 50 25"
      repeatCount="indefinite"
    ></animateTransform>
  </rect>
</svg>

五、实战一:环形进度条

目标:圆环随百分比增长,颜色从红渐变到蓝,中间显示数字。

原理一句话:周长是 2πr,用 stroke-dasharray="可见长度, 足够大的数" 只画出其中一段,改「可见长度」就是改进度。半径 300,周长约 1885。

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>环形进度条</title>
    <style>
      body { text-align: center; }
      .text { text-anchor: middle; }
    </style>
  </head>
  <body>
    <svg height="700" width="700">
      <!-- 底色的圆环 -->
      <circle cx="350" cy="350" r="300" fill="none" stroke="#ddd" stroke-width="40"></circle>
      <!-- 进度圆环:从 12 点方向开始长 -->
      <circle
        class="progress"
        cx="350"
        cy="350"
        r="300"
        fill="none"
        stroke="red"
        stroke-width="40"
        stroke-linecap="round"
        stroke-dasharray="0,10000"
        transform="rotate(-90,350,350)"
      ></circle>
      <!-- 中间的数字 -->
      <text class="text" x="350" y="350" font-size="200" fill="red" dominant-baseline="central">0</text>
    </svg>
    <script>
      const progress = document.querySelector(".progress");
      const text = document.querySelector(".text");
      // 周长只算一次:2πr ≈ 1885
      const length = Math.floor(2 * Math.PI * parseFloat(progress.getAttribute("r")));

      function render(percent) {
        // 可见长度 = 周长 × 百分比
        const visible = (percent * length) / 100;
        // 红 rgb(255,0,0) → 蓝 rgb(0,191,255)
        const red = Math.round(255 + ((0 - 255) / 100) * percent);
        const green = Math.round(0 + ((191 - 0) / 100) * percent);
        const blue = Math.round(0 + ((255 - 0) / 100) * percent);
        const color = `rgb(${red},${green},${blue})`;
        progress.setAttribute("stroke-dasharray", visible + ",10000");
        progress.setAttribute("stroke", color);
        text.textContent = percent + "%";
        text.setAttribute("fill", color);
      }

      let n = 0;
      setInterval(() => {
        n = n > 100 ? 0 : n + 1;
        render(n);
      }, 30);
    </script>
  </body>
</html>

两个细节:rotate(-90, 350, 350) 把起点从 3 点方向挪到 12 点方向,否则进度从右边开始长;stroke-linecap="round" 让两端变圆,更像进度条。

六、实战二:条形统计图

目标:七天订单量的柱状图,带坐标轴、刻度和随机配色。

换算关系:纵轴 15 格、每格 1000 单,yLength = 450 / 15 = 30 像素,于是柱高 = 订单数 / 1000 × 30,柱顶 y = 600 - 柱高。

柱子和刻度要对齐:刻度线画在 150 + listLength * i,柱宽 20,所以柱子的 x 取 140 + listLength * i,柱心才正好落在刻度上。

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <title>条形统计图</title>
    <style>
      .coordinate { stroke: #999; stroke-width: 2; }
      .scale { stroke: orangered; stroke-width: 1; }
    </style>
  </head>
  <body>
    <svg width="1000" height="700">
      <g id="coordinate">
        <line class="coordinate" x1="50" y1="600" x2="950" y2="600"></line>
        <path d="M 925,590 L 950,600 L 925,610"></path>
        <text x="920" y="630">时间</text>
        <line class="coordinate" x1="100" y1="650" x2="100" y2="50"></line>
        <path d="M 90,75 L 100,50 L 110,75"></path>
        <text x="50" y="70">订单</text>
      </g>
      <g id="scalex"></g>
      <g id="scaley"></g>
      <g id="list"></g>
    </svg>
    <script>
      const data = [
        { time: "8月21日", order: 12000 },
        { time: "8月22日", order: 13000 },
        { time: "8月23日", order: 11000 },
        { time: "8月24日", order: 14000 },
        { time: "8月25日", order: 15000 },
        { time: "8月26日", order: 12000 },
        { time: "8月27日", order: 11000 },
      ];

      const scalex = document.getElementById("scalex");
      const scaley = document.getElementById("scaley");
      const list = document.getElementById("list");

      // 每根柱子占的横向宽度,7 天分 700px
      const listLength = Math.floor(700 / data.length);
      // 纵向一格代表 1000 单:450px / 15 格
      const yLength = 450 / 15;

      // 横轴刻度与日期
      for (let i = 1; i <= data.length; i++) {
        const x = 150 + listLength * i;
        scalex.innerHTML +=
          `<line class="scale" x1="${x}" y1="600" x2="${x}" y2="580"></line>` +
          `<text x="${x}" y="620" text-anchor="middle">${data[i - 1].time}</text>`;
      }

      // 纵轴刻度,每格 1000
      for (let j = 1; j <= 15; j++) {
        const y = 600 - yLength * j;
        scaley.innerHTML +=
          `<line class="scale" x1="100" y1="${y}" x2="120" y2="${y}"></line>` +
          `<text x="50" y="${y}">${1000 * j}</text>`;
      }

      // 柱子:柱宽 20,x 取刻度左移 10px,柱心才落在刻度上
      for (let i = 1; i <= data.length; i++) {
        const x = 140 + listLength * i;
        const height = (data[i - 1].order / 1000) * yLength;
        const color = `rgb(${parseInt(Math.random() * 255)},${parseInt(
          Math.random() * 255
        )},${parseInt(Math.random() * 255)})`;
        list.innerHTML += `<rect x="${x}" y="${600 - height}" width="20" height="${height}" fill="${color}"></rect>`;
      }
    </script>
  </body>
</html>

七、几个不报错但会浪费一下午的坑

  • 属性名拼错不会报错。stroke-dasharry 会被当成未知属性直接忽略,圆环永远是完整的——先查拼写。
  • 超出画布也不会报错。<rect y="50" height="200"> 放进 180 高的画布,下半截被裁掉,控制台一声不响。
  • 用 <img> 引入就拿不到 DOM,改不了颜色;想让图标跟随文字颜色,得内联后用 currentColor。
  • 内联 SVG 对读屏软件默认是一片空白,加上 role="img" 和 <title> 才会被读出来。
  • 复杂路径别手写。十几个锚点以上交给设计工具导出,手写的坐标既难维护也难改。

八、元素图例

每个元素画出来长什么样,一图一句。

  • circle:圆心加半径

  • rect:左上角加宽高

  • ellipse:中心加两个半径

  • line:两个端点

  • polyline:一串端点,不闭合

  • polygon:一串端点,首尾相连

  • text:从基线开始画

  • use:复制一份并平移

  • g:把几个形状打包

  • defs:只定义,画面上不出现

  • pattern:一块图案平铺整个区域

  • image:把位图塞进 SVG 里

参考资料

  • MDN:SVG 元素参考——形状、容器与动画元素的完整清单,本文表格与之逐条对应。核对日期 2026-11-14。
  • MDN:viewBox——四个值的顺序与缩放规则的官方说明。核对日期 2026-11-14。
  • MDN:stroke-dasharray——虚线段长与间距的定义,环形进度条的原理出处。核对日期 2026-11-14。
  • MDN:preserveAspectRatio——宽高比不一致时的对齐与缩放策略。核对日期 2026-11-14。
  • W3C:SVG 2 规范——属性语义的最终依据,MDN 有出入时以它为准。核对日期 2026-11-14。
© 2026 Carreyda