使用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)
}
})
}
感谢阅读
如有问题,欢迎留言指出,一起学习,一起进步