but c...">

Set img.src to dynamic svg element

I know that I can set the svg file as src of the HTML img element as follows:

 <img src="mySVG.svg"/> 

but can I somehow set the dynamic SVG element as src for img ?

 <svg id="mySVGElement"> ... </svg> <img src="?"/> 
+4
source share
2 answers

You can do this using 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 (change), you will need to re-run this code every time the SVG element has 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 SVG document that is referenced, and that the link is active: changes to the original are immediately reflected in <use> .

+10
source

Not exactly, according to the SVG specification, the <img> should refer to the complete file. It looks like you want something like <use xlink:href="#mySVGElement"/>

+1
source

All Articles