SVG,即可缩放矢量图形(Scalable Vector Graphics),是一种基于可扩展标记语言(XML)的图形图像格式。SVG格式的图像具有矢量特性,可以无限放大而不失真,非常适合网页设计、移动应用和印刷品等。本教程将从零开始,带你轻松掌握SVG绘图的基础。
一、SVG基本概念
1.1 SVG文件结构
SVG文件以XML格式存储,包含一个根元素<svg>,它定义了整个图形的范围和属性。以下是SVG文件的基本结构:
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<!-- 图形内容 -->
</svg>
1.2 SVG元素
SVG图形由多种元素组成,常见的有:
<circle>:圆形<rect>:矩形<line>:直线<polyline>:多边形<polygon>:多边形的闭合版本<ellipse>:椭圆<path>:自定义路径
二、SVG绘图入门
2.1 绘制基本图形
2.1.1 绘制圆形
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
2.1.2 绘制矩形
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<rect x="50" y="50" width="100" height="100" fill="blue" />
</svg>
2.1.3 绘制直线
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<line x1="10" y1="10" x2="190" y2="190" stroke="green" />
</svg>
2.2 调整图形属性
SVG图形具有丰富的属性,如fill(填充色)、stroke(边框色)、stroke-width(边框宽度)、transform(变换)等。
2.2.1 调整颜色
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<circle cx="50" cy="50" r="40" fill="red" />
<rect x="50" y="50" width="100" height="100" fill="blue" />
<line x1="10" y1="10" x2="190" y2="190" stroke="green" />
</svg>
2.2.2 调整边框
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<circle cx="50" cy="50" r="40" fill="red" stroke="black" stroke-width="3" />
<rect x="50" y="50" width="100" height="100" fill="blue" stroke="black" stroke-width="3" />
<line x1="10" y1="10" x2="190" y2="190" stroke="green" stroke-width="3" />
</svg>
2.3 绘制复杂图形
2.3.1 绘制路径
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<path d="M10 10 H 190 V 190 H 10 Z" fill="none" stroke="black" stroke-width="3" />
</svg>
三、SVG高级应用
3.1 动画
SVG支持多种动画效果,如<animate>、<animateTransform>等。
3.1.1 基本动画
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<circle cx="50" cy="50" r="40" fill="red">
<animate
attributeName="cx"
from="50"
to="150"
dur="2s"
repeatCount="indefinite"
/>
</circle>
</svg>
3.2 与CSS结合
SVG图形可以与CSS样式结合,实现更丰富的视觉效果。
3.2.1 应用CSS样式
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="200"
height="200"
viewBox="0 0 200 200"
>
<circle cx="50" cy="50" r="40" fill="red" class="animated" />
<style>
.animated {
animation: move 2s infinite;
}
@keyframes move {
0% {
cx: 50;
}
100% {
cx: 150;
}
}
</style>
</svg>
四、总结
通过本教程,相信你已经对SVG绘图有了基本的了解。SVG绘图具有很多优势,如矢量特性、丰富的动画效果、与CSS结合等。希望你在今后的工作中能充分利用SVG的优势,创作出更多优秀的作品。