html%3ca%3e标签改字体颜色,从外部源加载到img标签时更改SVG的填充颜色 - javascript代码 - 源码查...

问题

I have quite a few SVG icons saved in different *.svg files. If I insert them into the page directly I can freely control their colors with the fill css option.

My trouble comes that I need to change the color of the svg and then display it in an img tag, because an important for the project library can only work with that. Is there a solution to my predicament?

graphic.svg

I need to be able to change the color of the svg and receive similar or the same end result. Is this even possible?

EDIT

Is it possible to include javascript in the svg file that will read parameters and change color accordingly? For example:

graphic.svg?fill=fff

I am not sure how can this be achieved.

解决方法

You can pass your svg doc as a dataURL :

So, either you download the file through xhr, append it to an svg element and then convert it to this dataURL,

var parser = new DOMParser();

var svgDoc = parser.parseFromString(xhr.response, "image/svg+xml");

svgDoc.querySelector('#yourElement').setAttributeNS(null, 'fill', yourColor);

var dataURL = encodeURIComponent(new XMLSerializer().serializeToString(svgDoc));

img.src = dataURL;

or you load it through an or an element and then convert its contentDocument :

var obj = document.createElement('object');

obj.src = "path/to/your/file.svg";

obj.onload = function(){

var svgDoc = obj.contentDocument;

svgDoc.querySelector('#yourElement').setAttributeNS(null, 'fill', yourColor);

var dataURL = encodeURIComponent(new XMLSerializer().serializeToString(svgDoc));

img.src = dataURL;

}

Of course, these solutions are limited by the cross-origin policies.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值