微信小程序修改svg颜色
背景:后台可配置主题色,svg图标需要使用主题色
微信小程序虽然不支持svg标签,但是Image标签支持svg,不过跟静态图一样,没法改颜色啥的。
方法:通过wx.getFileSystemManager().readFile()来获取文件,然后匹配其中的fill属性并修改属性值,然后把新生成的svg内容转成base64,加上前缀传给image标签的src。
需要注意的是
①如果svg是多种颜色的那种,需要自己手动修改一下svg文件,确保自己程序中修改的fill属性是自己想要修改的那个
②readFile的参数filePath得是放在静态文件夹(static或者public)中的文件地址,要不然控制台报错找不到文件
<template>
<image :src="svgIcon || ''" mode="aspectFill"></image>
</template>
<script>
import { loadImage } from '@/utils/loadImage'
import { Base64 } from "@/utils/base64";
const base64 = new Base64()
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true,
},
svgStyle: {
type: Object,
default: () => {
return {}
},
}
},
data() {
return {
svgIcon: ''
}
},
computed: {},
methods: {
changeColor(sourceFile, color) {
let newSvg;
// if (/fill=".*?"/.test(sourceFile)) {
// newSvg = sourceFile.replace(/fill=".*?"/g, `fill="${color}"`); // SVG有默认色 svg有些需要自己修改其中的fill属性
// } else {
newSvg = sourceFile.replace(/<svg /g, `<svg fill="${color}" `); // 无默认色
// }
return newSvg
}
},
mounted() {
let that = this
const fs = wx.getFileSystemManager()
fs.readFile({
filePath: `static/svg/${that.iconClass}.svg`,
// filePath: `static/svg/person.svg`,
encoding: 'utf-8',
position: 0,
success(res) {
let sourceFile = res.data;
let newSvg = that.changeColor(sourceFile, that.svgStyle.color);
let base64Data = base64.encode(newSvg);
that.svgIcon = `data:image/svg+xml;base64,${base64Data}`
if (that.iconClass === 'person') {
console.log(newSvg)
}
if (that.iconClass === 'time') {
console.log(newSvg)
}
},
fail(res) {
console.error(res)
}
})
}
}