简述SVG样式
SVG(Scalable Vector Graphics)是一种基于 XML 的矢量图形格式,支持丰富的样式设置。SVG 的样式可以通过多种方式定义和应用,以下是 SVG 样式的简述:
1. 内联样式
-
方法:
- 直接在 SVG 元素的
style属性中定义样式。
- 直接在 SVG 元素的
<circle cx="50" cy="50" r="40" style="fill: red; stroke: black; stroke-width: 3;" />
-
优点:
- 简单直接,优先级高。
-
缺点:
- 不利于复用和维护。
2. 内部样式表
-
方法:
- 在 SVG 文件中使用
<style>标签定义样式。
- 在 SVG 文件中使用
<svg>
<style>
circle {
fill: red;
stroke: black;
stroke-width: 3;
}
</style>
<circle cx="50" cy="50" r="40" />
</svg>
-
优点:
- 样式可复用,便于维护。
-
缺点:
- 仅适用于当前 SVG 文件。
3. 外部样式表
-
方法:
- 使用外部 CSS 文件定义 SVG 样式,并通过
<link>或<?xml-stylesheet?>引入。
- 使用外部 CSS 文件定义 SVG 样式,并通过
<?xml-stylesheet href="styles.css" type="text/css"?>
<svg>
<circle cx="50" cy="50" r="40" class="my-circle" />
</svg>
/* styles.css */
.my-circle {
fill: red;
stroke: black;
stroke-width: 3;
}
-
优点:
- 样式可跨文件复用,便于统一管理。
-
缺点:
- 需要额外 HTTP 请求。
4. 属性样式
-
方法:
- 直接在 SVG 元素的属性中定义样式。
<circle cx="50" cy="50" r="40" fill="red" stroke="black" stroke-width="3" />
-
优点:
- 简单直接。
-
缺点:
- 不利于复用和维护。
5. 常用样式属性
-
填充和描边:
-
fill:设置填充颜色。 -
stroke:设置描边颜色。 -
stroke-width:设置描边宽度。 -
stroke-opacity:设置描边透明度。 -
fill-opacity:设置填充透明度。
-
-
渐变和图案:
-
使用
<linearGradient>和<radialGradient>定义渐变。 -
使用
<pattern>定义图案。
-
-
文本样式:
-
font-family:设置字体。 -
font-size:设置字体大小。 -
text-anchor:设置文本对齐方式(如start、middle、end)。 -
变换:
-
transform:设置变换(如平移、旋转、缩放)。
-
6. 示例代码
以下是一个使用多种样式方式的 SVG 示例:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<!-- 内部样式表 -->
<style>
.my-rect {
fill: blue;
stroke: green;
stroke-width: 2;
}
</style>
<!-- 内联样式 -->
<circle cx="50" cy="50" r="40" style="fill: red; stroke: black; stroke-width: 3;" />
<!-- 属性样式 -->
<rect x="100" y="100" width="80" height="60" fill="yellow" stroke="purple" stroke-width="4" />
<!-- 使用内部样式表 -->
<rect x="20" y="120" width="60" height="40" class="my-rect" />
<!-- 渐变填充 -->
<defs>
<linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="150" cy="50" rx="40" ry="30" fill="url(#gradient)" />
</svg>
总结
SVG 样式可以通过内联样式、内部样式表、外部样式表和属性样式等方式定义。常用样式属性包括填充、描边、渐变、文本样式和变换等。合理使用这些样式方式,可以创建出丰富且灵活的矢量图形。
更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github