SVG2
以下是SVG的一些常见用法小结:
1. 基本形状绘制
SVG允许直接在HTML中绘制基本形状,如矩形(<rect>
)、圆形(<circle>
)、椭圆(<ellipse>
)、线条(<line>
)和多边形(<polygon>
和 <polyline>
)。
1<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
2 <rect width="100" height="100" fill="red"/>
3 <circle cx="50" cy="50" r="40" fill="green"/>
4 <ellipse cx="50" cy="50" rx="30" ry="20" fill="blue"/>
5 <line x1="0" y1="0" x2="100" y2="100" stroke="black"/>
6 <polygon points="20,30 40,80 70,50 80,90" fill="yellow"/>
7</svg>
2. 路径绘制
使用<path>
元素,可以通过一系列的路径命令绘制复杂的形状。
1<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
2 <path d="M10 10 H 190 V 190 H 10 L 10 10" stroke="black" fill="transparent"/>
3</svg>
3. 文本显示
在SVG中,可以使用<text>
元素来显示文本。
1<svg width="400" height="100" xmlns="http://www.w3.org/2000/svg">
2 <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-size="20" fill="black">SVG Text</text>
3</svg>
4. 应用样式
SVG支持CSS样式,可以为图形元素设置样式,如颜色、描边、阴影等。
1<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
2 <rect width="100" height="100" style="fill:red; stroke:blue; stroke-width:3"/>
3</svg>
5. 交互性
SVG元素可以绑定事件监听器,如点击、悬停等,实现交互效果。
1<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
2 <circle cx="50" cy="50" r="40" fill="green" onclick="alert('Circle clicked!')"/>
3</svg>
6. 动画
SVG支持简单动画,通过<animate>
元素实现。
1<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
2 <circle cx="50" cy="50" r="40" fill="green">
3 <animate attributeName="cx" from="50" to="150" dur="2s" repeatCount="indefinite"/>
4 </circle>
5</svg>
7. 滤镜效果
SVG提供了多种滤镜效果,如模糊、发光、阴影等。
1<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
2 <defs>
3 <filter id="f1" x="0" y="0">
4 <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
5 </filter>
6 </defs>
7 <circle cx="75" cy="75" r="50" fill="blue" filter="url(#f1)"/>
8</svg>
8. 组合和变换
使用<g>
元素对多个图形进行组合,并通过transform
属性实现图形的移动、缩放、旋转等变换。
1<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
2 <g transform="translate(50,50) scale(0.5)">
3 <rect width="100" height="100" fill="red"/>
4 <circle cx="50" cy="50" r="40" fill="green"/>
5 </g>
6</svg>
9. 嵌入和引用
SVG可以内嵌在HTML中,也可以作为外部文件被引用。
1<!-- 内嵌SVG -->
2<svg xmlns="http://www.w3.org/2000/svg">
3 <!-- SVG内容 -->
4</svg>
5
6<!-- 引用外部SVG文件 -->
7<object type="image/svg+xml" data="image.svg" width="100" height="100"></object>
10. 响应式设计
SVG图形的矢量特性使其非常适合响应式设计,可以轻松适应不同屏幕尺寸。
SVG的灵活性和多功能性使其成为网页设计和图形处理的强大工具。通过上述用法,开发者可以创建丰富、交互式的图形和动画,增强用户体验。