微信小程序修改svg颜色

本文介绍了如何在微信小程序中,利用后台配置的主题色,通过读取SVG文件并修改fill属性,将SVG转换为Base64格式,实现动态更换颜色的功能。
摘要由CSDN通过智能技术生成

微信小程序修改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)
      }
    })
  }
}

base64

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值