问题描述
我知道我可以将svg文件设置为HTML img
元素的 src
,如下所示:
< img src =mySVG.svg/>
但我可以以某种方式将动态SVG元素设置为 src
img
?
< svg id = mySVGElement >
...
< / svg>
< img src =?/>
您可以使用JavaScript完成此操作:
var svg = document.querySelector('svg'),
img = document.querySelector('img');
setImageToSVG(img,svg);
函数setImageToSVG(img,svg){
var xml =(new XMLSerializer).serializeToString(svg);
img.src =data:image / svg + xml; charset = utf-8,+ xml;
$ b如果你的SVG元素是动态的(改变),那么你需要重新每当SVG元素发生变化时运行此代码。
演示:
或者,这里有一个演示,显示@ Robert的答案,使用另一个< svg>
元素来引用第一个live:
演示:
< svg id =srcxmlns =http://www.w3.org/2000/svg...>
< / svg>
< svg xmlns =http://www.w3.org/2000/svgxmlns:x =http://www.w3.org/1999/xlink...>
< use x:href =#srcx =80y =30width =100height =100/>
< / svg>
演示还显示您可以调整大小并以其他方式转换引用的SVG文档,并且参考 live:对原始内容的更改立即反映在< use>
中。
I know that I can set a svg file as the src
of an HTML img
element like this:
<img src="mySVG.svg"/>
but can I somehow set a dynamic SVG element as the src
of an img
?
<svg id="mySVGElement">
...
</svg>
<img src="?"/>
解决方案 You can do this with JavaScript:
var svg = document.querySelector('svg'),
img = document.querySelector('img');
setImageToSVG(img,svg);
function setImageToSVG(img,svg){
var xml = (new XMLSerializer).serializeToString(svg);
img.src = "data:image/svg+xml;charset=utf-8,"+xml;
}
If your SVG element is dynamic (changing) then you would need to re-run this code each time the SVG element changed.
Demo: http://jsfiddle.net/3PfcC/
Alternatively, here's a demo showing @Robert's answer, using another <svg>
element to reference the first, live:
Demo: http://jsfiddle.net/3PfcC/3/
<svg id="src" xmlns="http://www.w3.org/2000/svg" …>
<!-- Your SVG here -->
</svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:x="http://www.w3.org/1999/xlink" …>
<use x:href="#src" x="80" y="30" width="100" height="100" />
</svg>
The demo also shows that you can resize and otherwise transform the referenced SVG document, and that the reference is live: changes to the original are immediately reflected in the <use>
.
这篇关于将img.src设置为动态svg元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!