Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding more svg elements to my document at runtime

Tags:

javascript

svg

I have an html file, I'm adding am element to it dynamically, then a rectangle. Works well in the different browsers (ignoring IE). When I try to use the same method to dynamically create an element, it does not work in Chrome or Safari, only in Opera. Is my syntax wrong, or does webkit probably just not support adding elements at runtime? (the same element works fine if I declare it as tags up-front instead). Maybe I'm not supposed to use appendChild() with these types of nodes? Here's what I have, you should be able to dump it into an html file and run it. If anyone has any idea if there's a way around this, it'd be great:

<html>
<head>
  <script>

    window.onload = function() {
        var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
        svg.setAttribute('version', '1.1');
        svg.setAttribute('width', '800px');
        svg.setAttribute('height', '400px');
        document.body.appendChild(svg);

        var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
        rect.setAttribute("id", "myrect"); 
        rect.setAttribute("fill","red");
        rect.setAttribute("stroke","black");
        rect.setAttribute("stroke-width","5");
        rect.setAttribute("x", "100");
        rect.setAttribute("y", "100");
        rect.setAttribute("width", "100");
        rect.setAttribute("height", "50");
        svg.appendChild(rect);

        var anim = document.createElementNS('http://www.w3.org/2000/svg','animate');
        anim.setAttribute("attributeName", "width");
        anim.setAttribute("from", "100");
        anim.setAttribute("to", "400");
        anim.setAttribute("dur", "10s");
        anim.setAttribute("begin", "0s");
        anim.setAttribute("fill", "freeze");
        rect.appendChild(anim);
    }

</script>
</head>

<body>
</body>

like image 421
user246114 Avatar asked Jan 28 '10 16:01

user246114


1 Answers

You really should use setAttributeNS(null, ...) when using namespace calls like document.createElementNS().

From xmlgraphics.apache.org/batik/faq.html

However, it is important to know that some implementations make a difference between setAttribute(x, y) and setAttributeNS(null, x, y), so it is good practice to use setAttributeNS which is the only guaranteed interoperable way of setting attributes in a namespace aware DOM implementation.

like image 82
Kyle Butt Avatar answered Oct 20 '22 08:10

Kyle Butt