Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create svg rectangle using javascript event

Tags:

javascript

svg

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);

  }
like image 774
chiyango Avatar asked Sep 14 '26 12:09

chiyango


1 Answers

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>
like image 76
Robert Longson Avatar answered Sep 16 '26 02:09

Robert Longson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!