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);
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With