Trying to draw a dynamic rectangle in SVG
Posted
by Shaun
on Stack Overflow
See other posts from Stack Overflow
or by Shaun
Published on 2010-04-05T19:02:10Z
Indexed on
2010/04/05
19:03 UTC
Read the original article
Hit count: 310
svg
|JavaScript
To be more specific, here are the steps I need:
onmousedown - set x and y of rect as mouse coordinates
onmousemove - using the current x and y mouse coordinates calculate height and width of the rect, set these and append
onmouseup - remove the rectangle, and call a function based off some calculations from the rect.
Here is what I have but isn't quite working (right now I have it drawing a line to make it simpler):
onmousedown: startbox(evt)
function startbox(evt)
{
if(evt.button === 0)
{
x1 = evt.clientX + div.scrollLeft-5;
y1 = evt.clientY + div.scrollTop-30;
obj.setAttributeNS(null, "x1", x1);
obj.setAttributeNS(null, "y1", y1);
Root.setAttributeNS(null, "onmousemove", "updatebox(evt)");
}
}
onmousemove: updatebox(evt)
function updatebox(evt)
{
if(evt.button === 0)
{
x2 = evt.clientX + div.scrollLeft-5;
y2 = evt.clientY + div.scrollTop-30;
Root.appendChild(.obj);
w = Math.abs(x2-x1);
h = Math.abs(y2-y1);
var strokecolor;
if(w>20 && h>20)
{
strokecolor = "green";
validbox = true;
}
else
{
strokecolor = "red";
validbox = false;
}
var Attr={
x2:x2,
y2:y2,
stroke:strokecolor
}
assignAttr(obj, Attr); //just loops thru adding multiple attributes
}
}
onmouseup: endbox()
function endbox(evt)
{
if(evt.button===0)
{
Root.setAttributeNS(null, "onmousemove", "");
Root.removeChild(obj);
if(validbox)
{
//do stuff
validbox = !validbox;
}
}
}
Some of my problems with this are: Its slow in Chrome making drawing the line/rect feel sluggish. It won't work two times in a row. This is the real problem that I can't fix.
Any and all feedback is welcome.
© Stack Overflow or respective owner