在使用Uniapp开发小程序过程中,想使用svg图标并且支持svg颜色的修改,但是小程序不支持svg标签,因此通过以下方案解决小程序中使用svg,将svg作为背景图片并辅助以正则表达式替换对应的颜色、描边和描边宽度。 下面是直接替换的组件,支持本地SVG和远程加载SVG文件
<template>
<view class="icon" v-if="!!svgData" :style="{
width:`${width||size}rpx`,
height:`${height||size}rpx`,
backgroundImage:`url('data:image/svg+xml,${svgData}')`,
backgroundSize:'contain' }">
</view>
</template>
<script setup>
const props = withDefaults(defineProps<{
url : string,
color ?: string,
size ?: number,
width ?: number,
height ?: number,
stroke ?: string,
strokeWidth ?: number
}>(), {
url: "",
color: "",
size: 24
})
const svgData = ref();
const svgFile = ref()
const handleSvgContent = () => {
//替换颜色
let _replaceFill = props.color ? svgFile.value.replace(/fill=\s*"(?!transparent|none")[^"]*"/g, `fill="${props.color}"`) : svgFile.value;
if (props.stroke) {
_replaceFill = _replaceFill.replace(/stroke="[^"]*"/g, `stroke="${props.stroke}"`);
}
if (props.strokeWidth) {
_replaceFill = _replaceFill.replace(/stroke-width\s*=\s*["']?[\d.]+["']?/gi, `stroke-width="${props.strokeWidth}"`)
}
_replaceFill = _replaceFill.replace(/url\(#/, "url(%23");//替换#号
console.log(_replaceFill, '--replace fill', props)
svgData.value = encodeURIComponent(_replaceFill);
}
onBeforeMount(() => {
const fs = uni.getFileSystemManager();
svgFile.value = fs.readFileSync(props.url, 'utf-8');
nextTick(() => {
handleSvgContent();
})
})
watch([() => props.color], () => {
nextTick(() => {
handleSvgContent();
})
})
watch([() => props.url], () => {
const fs = uni.getFileSystemManager();
svgFile.value = fs.readFileSync(props.url, 'utf-8');
nextTick(() => {
handleSvgContent();
})
})
</script>
<style lang="scss">
.icon {
background-size: contain;
background-repeat: no-repeat;
}
</style>