Note that there are some explanatory texts on larger screens.

plurals
  1. POProgrammatically creating an SVG image element with javascript
    text
    copied!<p>Like my title says, I'm trying to programmatically creating an SVG image element in a HTML page using javascript. For some reason my basic javascript code isn't working, however if I use the raphaeljs library it works fine. So there's obviously a problem with my js - I just can't seem to figure out what it is.</p> <p>(note: the target browser is FF4+)</p> <p>Here is the basic page with an html version of what I'm trying to achieve up the top: </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="http://raphaeljs.com/raphael.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="test1" height="200px" width="200px"&gt; &lt;image id="testimg1" xlink:href="http://i.imgur.com/LQIsf.jpg" width="100" height="100" x="0" y="0"/&gt; &lt;/svg&gt; &lt;hr /&gt; &lt;p id="testP1"&gt; &lt;/p&gt; &lt;hr /&gt; &lt;p id="testP2"&gt; &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And here is my javascript:</p> <pre><code>var paper = Raphael(document.getElementById("testP1"), 200, 200); paper.image("http://i.imgur.com/LQIsf.jpg", 0,0, 100, 100); var svg = document.createElementNS('http://www.w3.org/2000/svg','svg'); svg.setAttributeNS('http://www.w3.org/2000/svg','xlink','http://www.w3.org/1999/xlink'); svg.setAttributeNS('http://www.w3.org/2000/svg','height','200'); svg.setAttributeNS('http://www.w3.org/2000/svg','width','200'); svg.setAttributeNS('http://www.w3.org/2000/svg','id','test2'); var svgimg = document.createElementNS('http://www.w3.org/2000/svg','image'); svgimg.setAttributeNS('http://www.w3.org/2000/svg','height','100'); svgimg.setAttributeNS('http://www.w3.org/2000/svg','width','100'); svgimg.setAttributeNS('http://www.w3.org/2000/svg','id','testimg2'); svgimg.setAttributeNS('http://www.w3.org/1999/xlink','href','http://i.imgur.com/LQIsf.jpg'); svgimg.setAttributeNS('http://www.w3.org/2000/svg','x','0'); svgimg.setAttributeNS('http://www.w3.org/2000/svg','y','0'); svg.appendChild(svgimg); document.querySelector('#testP2').appendChild(svg); </code></pre> <p>Live example: <a href="http://jsfiddle.net/Yansky/UVFBj/5/" rel="noreferrer">http://jsfiddle.net/Yansky/UVFBj/5/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload