HTML5 SVG 完整教程
SVG(Scalable Vector Graphics)即可伸缩矢量图形,是一种用 XML 描述二维图形的语言。SVG 是矢量图形,可以无限缩放而不失真。
基本用法
基础 SVG 示例
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="80" fill="orange"/>
</svg>
基本图形
基本图形示例
<svg width="300" height="150">
<!-- 矩形 -->
<rect x="10" y="10" width="80" height="50" fill="steelblue"/>
<!-- 圆形 -->
<circle cx="150" cy="50" r="30" fill="coral"/>
<!-- 椭圆 -->
<ellipse cx="250" cy="50" rx="40" ry="25" fill="gold"/>
<!-- 直线 -->
<line x1="10" y1="100" x2="100" y2="130" stroke="green" stroke-width="3"/>
</svg>
路径 - path
路径示例
<svg width="200" height="150">
<!-- 贝塞尔曲线 -->
<path d="M 10 100 Q 50 10 100 100 T 190 100"
fill="none" stroke="steelblue" stroke-width="3"/>
</svg>
/* 命令说明:
* M - 移动到起点
* Q - 二次贝塞尔曲线
* T - 平滑二次贝塞尔曲线
* L - 直线
* Z - 闭合路径
*/
渐变填充
渐变示例
<svg width="200" height="100">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%">
<stop offset="0%" style="stop-color:rgb(255,255,0)"/>
<stop offset="100%" style="stop-color:rgb(255,0,0)"/>
</linearGradient>
</defs>
<rect width="200" height="100" fill="url(#grad)"/>
</svg>
SVG 动画
动画示例
<svg width="200" height="100">
<circle cx="30" cy="50" r="20" fill="steelblue">
<animate
attributeName="cx"
from="30" to="170"
dur="3s"
repeatCount="indefinite"/>
</circle>
</svg>
常见问题
SVG 和 Canvas 有什么区别?
SVG 是矢量图形,放大不失真,支持 DOM 事件;Canvas 是位图,适合大量对象和频繁重绘的游戏场景。
SVG 可以交互吗?
可以,SVG 支持 DOM 事件,可以为每个元素添加点击、悬停等交互效果。
💻 在线代码编辑器
👁️ 预览效果