因为要做uni-app换肤,所以有一些icon使用svg,然后根据主题色进行着色,所以有这个需求下面我说一下解决方法
补充说明一下,这种方式处理起来感觉有点麻烦,最后我还是使用的iconfont去解决的,这里提供一下改变svg颜色的方法
首先准备一张svg图
如下
第二把图片转成data:image,可以利用如下网站https://codepen.io/jakob-e/pen/doMoML转
得到结果如下:
let svgClock = "data:image/svg+xml,%3C?xml version='1.0' encoding='utf-8'?%3E %3C!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --%3E %3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E %3Csvg version='1.1' id='图层_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='40px' height='40px' viewBox='10 12 20 20' xml:space='preserve'%3E %3Cg display='none'%3E %3Cpath display='inline' d='M28.902,26.002C32.561,23.702,35,19.641,35,15c0-7.18-5.82-13-13-13C14.82,2,9,7.82,9,15 c0,4.641,2.439,8.702,6.098,11.003C7.466,28.259,2,34.12,2,41c0,1.657,1.343,3,3,3h34c1.657,0,3-1.343,3-3 C42,34.12,36.534,28.258,28.902,26.002z M12,15c0-5.514,4.486-10,10-10c5.514,0,10,4.486,10,10s-4.486,10-10,10 C16.486,25,12,20.514,12,15z M5,41c0-7.18,7.611-13,17-13c9.389,0,17,5.82,17,13H5z'/%3E %3Cpath display='inline' d='M26.232,16.438c-0.807-0.21-1.619,0.274-1.826,1.077C24.121,18.619,23.131,19.39,22,19.39 s-2.121-0.771-2.406-1.876c-0.207-0.802-1.025-1.285-1.828-1.076c-0.802,0.208-1.284,1.026-1.076,1.828 c0.628,2.428,2.812,4.124,5.311,4.124s4.683-1.696,5.312-4.125C27.518,17.464,27.036,16.646,26.232,16.438z'/%3E %3C/g%3E %3Cg%3E %3Cpath fill='%23999999' d='M22,14c-4.418,0-8,3.582-8,8c0,4.418,3.582,8,8,8c4.418,0,8-3.582,8-8C30,17.582,26.418,14,22,14z M22,28.77c-3.732,0-6.769-3.037-6.769-6.77s3.037-6.769,6.769-6.769s6.77,3.037,6.77,6.769S25.732,28.77,22,28.77z'/%3E %3Cpath fill='%23999999' d='M26.556,21.385h-3.94v-3.941c0-0.316-0.275-0.572-0.615-0.572c-0.34,0-0.615,0.256-0.615,0.572v4.6 c0,0.147,0.061,0.279,0.159,0.38c0.005,0.005,0.01,0.012,0.015,0.017c0.006,0.006,0.012,0.011,0.019,0.017 c0.101,0.097,0.233,0.158,0.379,0.158h4.6c0.316,0,0.572-0.276,0.572-0.616S26.873,21.385,26.556,21.385z'/%3E %3C/g%3E %3C/svg%3E"
第三使用一个函数替换颜色
如下
const changeSvgColor = function(url, color){
let svgUrl = url.replace(/%23[a-zA-Z0-9]{6}/g, color.replace("#", "%23"));//这时候需要注意有的颜色是三个长度
return svgUrl;
}
第四使用
data() {
return {
svgData: '"' + svgClock + '"',
}
}
js
this.svgData = changeSvgColor(this.svgData, this.appColorStyle.themeColor);
效果如下: