SVG 矢量图形
svg 内联图形、circle/rect/line/path 基本形状、缩放不失真
SVG 矢量图形
SVG 是 XML 格式的矢量图——放大不失真、体积小、可用 CSS/JS 操控。
学完本章你将: 掌握 svg 内联图形、基本形状、渐变。
基本形状
html
<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
<!-- 矩形 -->
<rect x="10" y="10" width="80" height="60"
fill="tomato" stroke="black" stroke-width="2"/>
<!-- 圆形 -->
<circle cx="160" cy="40" r="35"
fill="gold" stroke="black" stroke-width="2"/>
<!-- 椭圆 -->
<ellipse cx="260" cy="40" rx="40" ry="25"
fill="lightblue" stroke="black" stroke-width="2"/>
<!-- 线段 -->
<line x1="320" y1="15" x2="380" y2="65"
stroke="green" stroke-width="3"/>
<!-- 折线 -->
<polyline points="10,100 50,80 90,120 130,90"
fill="none" stroke="purple" stroke-width="2"/>
<!-- 多边形(五角星简化) -->
<polygon points="200,80 220,130 270,130 230,155 245,200 200,175 155,200 170,155 130,130 180,130"
fill="orange" stroke="black"/>
<!-- 路径(最强大) -->
<path d="M 300 100 Q 350 60 400 100 T 500 100"
fill="none" stroke="blue" stroke-width="3"/>
</svg>
文字
html
<svg width="300" height="60">
<text x="10" y="40"
font-family="Arial" font-size="24"
fill="#333">
Hello SVG!
</text>
</svg>
vs Canvas
| SVG | Canvas |
|---|---|
| 矢量——缩放不失真 | 位图——放大会模糊 |
| 每个元素是 DOM 节点 | 像素级操作 |
| 适合图标、图表 | 适合游戏、动画 |
💡 图标优先用 SVG,复杂动画用 Canvas。