0

I want to create svg rectangle using javascript onmouseup event. What my problem is rectangle created(viewed through firebug) but i cant view it. Can any one help me.

click here

function doSomething()
  { 
var svgns = "http://www.w3.org/2000/svg";
        var rect = document.createElementNS(svgns, 'rect');
        rect.setAttributeNS(null, 'x', '150');
        rect.setAttributeNS(null, 'y', '150');
        rect.setAttributeNS(null, 'height', '50');
        rect.setAttributeNS(null, 'width', '50');
        rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff *         Math.random()).toString(16));
        document.getElementById('svgOne').appendChild(rect);

  }
chiyango
  • 401
  • 10
  • 20

2 Answers2

0

You can't display a <rect> element (or in general any SVG element) unless it's within an <svg> element. If you change your html so that it looks something like this...

<svg id="svgOne" width="200" height="200"></svg>

It works for me

function doSomething() {    
  var svgns = "http://www.w3.org/2000/svg";
  var rect = document.createElementNS(svgns, 'rect');
  rect.setAttribute('x', '150');
  rect.setAttribute('y', '150');
  rect.setAttribute('height', '50');
  rect.setAttribute('width', '50');
  rect.setAttribute('fill', '#'+Math.round(0xffffff *         Math.random()).toString(16));
  document.getElementById('svgOne').appendChild(rect);
}
svg {
  position: absolute;
  top: 0px;
  left: 200px;
}
<div id="myImgId" style="width: 200px; height: 200px; background:#000;" onmouseup="doSomething()" onmousedown="return false;">
</div>
<svg id="svgOne" width="200" height="200"></svg>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
0
<html>
  <head>
  </head>
  <body>
    <div id="didiyeu"></div>
    <script>
      function kotak(){
         // create svg tag
         var induk = document.createElementNS("http://www.w3.org/2000/svg","svg");
         // create svg element rectangle
         var kotak = document.createElementNS("http://www.w3.org/2000/svg","rect");
         // put some attibutes
             kotak.setAttribute("width","80");
             kotak.setAttribute("height","80");
         // put rectangle to svg element/tag called induk
            induk.appendChild(kotak);
         // then put into html
            document.getElementById("didiyeu").appendChild(induk);
      }
      // call the function
      kotak();
    </script>
  </body>
</html>

happy codding :)

Mang Jojot
  • 400
  • 4
  • 12