I just discovered this SVG thing you can do with XML to make pretty shapes and I can't do what I want to do. I don't know much about it so what I want to do might just not be possible anyway - maybe somebody here can help.
My goal is simply to add a new element to the XML document in the svg element - dynamically creating a new circle.
I can't figure out why it doesn't work so any help or information (even if its just to tell me I can't) is much appreciated
Below is some code illustrating what it is that's confusing me.
I don't get why I can't add an element using the appendChild or insertBefore functions. I've done various checks to make sure that the elements exist and stuff but when it comes to adding a new one it simply doesn't let me. I've left in a line that changes the color of the circle from red to purple although its not relevant to this really
Code: Select all
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="12cm" height="4cm" viewBox="0 0 1200 400" xmlns="http://www.w3.org/2000/svg" version="1.1" onload="init(this)">
<!-- Show outline of canvas using 'rect' element -->
<rect x="1" y="1" width="1198" height="398" fill="none" stroke="blue" stroke-width="2"/>
<circle id="ccc" cx="600" cy="200" r="100" fill="red" stroke="blue" stroke-width="10" />
<script id="sc" type="text/javascript">
var xmlns="http://www.w3.org/2000/svg"
function init(evt) {
if ( window.svgDocument == null ){
svgDocument = evt.ownerDocument;
}
var myE = svgDocument.getElementById('ccc');
var ppp = svgDocument.importNode(c(50,20,500,'red',4,'blue'), true);
s(myE,'fill', 'purple');
svgDocument.insertBefore(ppp,myE); //Node was not found
svgDocument.appendChild(ppp); //Node cannot be inserted at the specified point in the hierarchy
}
function c(r,t,l,cl,bw,bc){
x=svgDocument.createElementNS(xmlns,'circle');
s(x,'r',r);
s(x,'cy',t);
s(x,'cx',l);
s(x,'fill',cl);
s(x,'stroke-width',bw);
s(x,'stroke',bc);
return x;
}
function s(e,a,v){
e.setAttribute(a,v);
}
</script>
</svg>