Sid Prasad
Sid Prasad

Reputation: 157

Drawing an SVG dynamically using javascript

I'm trying to draw an isoceles triangle with it's top vertex in the middle of the screen.

I want to use JavaScript as screen sizes of different users can be different and hence, center of the screen must first be found out.

Here is my code:

function drawRect(){

        var w = $(document).width();
        var h = $(window).height();
        var halfh = h/2;
        var halfw = w/2;
        var svg = document.createElement("svg");
        var poly = document.createElement("polygon");
        svg.setAttribute("style", "position: fixed;");
        svg.setAttribute("height", ""+h);
        svg.setAttribute("width", ""+w);
        poly.setAttribute("points", ""+halfw+","+halfh+" 0,"+h+" "+w+","+h);
        poly.setAttribute("style", "fill:lime;stroke:purple;stroke-width:1");
        svg.appendChild(poly);

        var svgplace = document.getElementById("carpet");
        svgplace.appendChild(svg);
     }

No triangle appears on the screen. But, if I open the 'Inspect Element' console on chrome, and I modify the created html element slightly, it appears! (Any kind of small mod. Like adding a space in the middle somewhere)

Please help!

Thanks in advance

Upvotes: 2

Views: 3637

Answers (1)

zero298
zero298

Reputation: 26920

You need to be using

document.createElementNS("http://www.w3.org/2000/svg", "polygon");

SVG is in its own namespace aside from HTML. Therefore, you need to create elements that are in the SVG namespace using createElementNS.


Consider the following example that works in Chrome and Firefox

var newItem = document.createElementNS("http://www.w3.org/2000/svg", "circle");
newItem.setAttribute("cx", ((16 * 1) + 8));
newItem.setAttribute("cy", "50%");
newItem.setAttribute("r", 4);
newItem.setAttribute("fill", "#333333");

document.getElementById("target").appendChild(newItem);
<svg id="target">
</svg>

Upvotes: 3

Related Questions