微信小程序使用canvas修改svg图标颜色

使用canvas修改svg图标颜色

最近写公司项目遇到一个坑爹的需求,如下图:选择不同的板式,上面文字颜色,图标颜色都要跟着一起变化,因为板式数据都是从后台获取,我想这不是很简单嘛,直接让后台将图标一到给我就完事了。
想着美滋滋,现实很残酷,后台只给色值,没办法,只能想想其他办法,最后翻看了很多文档,最终选择使用svg来解决图标变色的问题在这里插入图片描述
话不多说,直接上代码

	data: {
		src:'/images/icon/1.svg',//图标
		imgurl:'',//页面展示的图标
		color:''//后台获取的颜色值
	},
	//动态修改svg颜色
	colorSVG(){
		var that = this
		wx.getFileSystemManager().readFile({
			filePath: that.data.src,
			encoding: 'binary',
			success: res => {
			  let basestr = res.data
			  if (that.data.color) {
				const strArr = basestr.split(/fill="#?[a-zA-Z0-9]{0,6}"/g)
				const oldcolorArr = basestr.match(/fill="#?[a-zA-Z0-9]{0,6}"/g)
				const newcolorArr = that.data.color.split(',')
				
				for (let i = 0; i < oldcolorArr.length; i++) {
					const color = newcolorArr
					if (color) {
						oldcolorArr[i] = 'fill="'+that.data.color+'"'
					}
				}
				let str = ''
				for (let i = 0; i < strArr.length; i++) {
					str += (strArr[i] + (oldcolorArr[i] ? oldcolorArr[i] : ''))
				}
				basestr = str
			  }
			  if (that.data.stroke) {
				const strArr = basestr.split(/stroke="#?[a-zA-Z0-9]{0,6}"/g)
				const oldcolorArr = basestr.match(/stroke="#?[a-zA-Z0-9]{0,6}"/g)
				const newcolorArr = that.data.stroke.split(',')
				for (let i = 0; i < oldcolorArr.length; i++) {
					const color = newcolorArr
					if (color) {
						oldcolorArr[i] = 'stroke="'+that.data.color+'"'
					}
				}
				let str = ''
				for (let i = 0; i < strArr.length; i++) {
				  str += (strArr[i] + (oldcolorArr[i] ? oldcolorArr[i] : ''))
				}
					basestr = str
				}
				const base64 = util.baseEncode(basestr)
				that.setData({
					imgurl : 'data:image/svg+xml;base64,' + base64
				})	  
			},
			fail:res =>{
				console.log(res)
			}
		})
	}

感谢阅读

如有问题,欢迎留言指出,一起学习,一起进步

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值