uniapp使用绘执svg
时间: 2025-06-28 18:16:53 浏览: 11
### 实现 UniApp 中的 SVG 绘制
#### 直接引用 SVG 文件
在 UniApp 项目中可以直接引入外部的 SVG 图像文件。通过 `<image>` 或者 HTML 的 `<img>` 标签来展示这些图像。这种方式适合于那些不需要频繁修改的静态图形。
```html
<template>
<view class="container">
<!-- 引入本地或网络上的SVG -->
<image :src="require('@/static/images/example.svg')" mode="widthFix"></image>
</view>
</template>
<script>
export default {
data() {
return {};
}
};
</script>
```
此方法简单快捷,适用于大多数场景下的图标显示需求[^1]。
#### 使用 Base64 编码嵌入
对于小型简单的矢量图,可以考虑将其转换成 base64 字符串并直接写入到样式属性 `background-image` 中去。这样做的好处是可以减少 HTTP 请求次数,提高页面加载速度。
```css
<style scoped>
.icon-base64 {
background-size: contain;
background-repeat: no-repeat;
width: 24px;
height: 24px;
}
</style>
<template>
<view class="container">
<view class="icon-base64" :style="{ backgroundImage: 'url(data:image/svg+xml;base64,' + encodedSvg }"></view>
</view>
</template>
<script>
import { defineComponent } from '@vue/composition-api';
// 将SVG转为Base64字符串
const rawSvg = '<svg ...></svg>';
const encodedSvg = Buffer.from(rawSvg).toString('base64');
export default defineComponent({
setup() {
return { encodedSvg };
},
});
</script>
```
这种方法特别适合用于内联的小型图标。
#### 利用 IconFont 服务
借助第三方字体库如阿里巴巴提供的 iconfont.cn 平台,开发者可以选择所需的图标集合成自定义字体包下载下来,在 CSS 文件里声明 @font-face 后即可轻松调用所需字符作为图标使用。
```less
@import url("//at.alicdn.com/t/font_abcde.css");
.icon-class:before{
content:"\e600";
font-family:'iconfont' !important;
font-style:normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
```
这不仅简化了管理流程还提高了渲染效率。
#### 创建自定义 SVG 组件
为了更好地控制和重用复杂的矢量图形逻辑,建议创建 Vue 单文件组件封装特定功能模块。比如下面的例子展示了怎样构建一个带参数配置接口的基础形状生成器:
```javascript
<!-- Circle.vue -->
<template>
<svg :width="size" :height="size" viewBox="-5 -5 10 10">
<circle cx="0" cy="0" r="4"/>
</svg>
</template>
<script>
export default {
props: ['size'],
};
</script>
```
之后可以在其他地方方便地实例化此类对象而无需重复编写相同代码片段。
#### 添加 SVG 动画效果
最后值得一提的是关于动态变化部分——即让原本静止不动的画面变得生动起来。可以通过设置 SMIL 属性、CSS transitions/animations 或 JavaScript 来达到目的;其中最推荐的方式还是后者因为它提供了最大的灵活性以及跨浏览器兼容性支持。
```xml
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect x="10" y="10" rx="15" ry="15" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5">
<animate attributeName="opacity" values="0;.75;0" dur="2s" repeatCount="indefinite"/>
</rect>
</svg>
```
上述例子利用内置标签实现了透明度渐变循环播放的效果。
#### 定义与应用箭头标记
当涉及到更复杂一些的内容创作时,例如带有方向指示作用的线条连接点之间,则可能需要用到 defs 和 marker 元素组合而成的新结构体。如下所示是如何定义一个三角形端点样式并通过 polyline 应用至实际路径上[^3]。
```xml
<svg width="120" height="120" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="10" markerWidth="10" markerHeight="10" orient="auto">
<path d="M 0 0 L 20 10 L 0 20 z"/>
</marker>
</defs>
<polyline points="10,90 50,80 90,20" fill="none" stroke="black" stroke-width="2" marker-end="url(#Triangle)"/>
</svg>
```
以上就是几种常见且实用的技术手段介绍,希望能帮助大家顺利开展基于 UniApp 框架下有关 SVG 处理的工作。
阅读全文
相关推荐

















