Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set img.src to dynamic svg element

Tags:

html

svg

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="?"/>
like image 255
Patrick Klug Avatar asked Aug 01 '12 06:08

Patrick Klug


2 Answers

This updates the accepted answer from Phrogz (8 years after it!)

The sample does not work on Chrome or Firefox (the image appears broken) changing to

  img.src = "data:image/svg+xml;base64,"+btoa(xml);

I am not sure of the reason why the original stopped working but this may help someone landing here.

like image 89
tru7 Avatar answered Sep 27 '22 18:09

tru7


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>.

like image 23
Phrogz Avatar answered Sep 27 '22 18:09

Phrogz