2

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

3
  • Check the attributes -- does anything change? Commented Oct 26, 2015 at 18:22
  • Check this post stackoverflow.com/questions/3290392/… Commented Oct 26, 2015 at 18:25
  • Why would you want to do it this way? Use a viewBox and then you can have fixed co-ordinates. Commented Oct 26, 2015 at 18:45

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.