Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawing a rectangle with mouse click and drag - javascript

I was trying to draw a rectangle (actually a selection box) in Javascript, to select the SVG elements that come in the selection. I tried to fix the code for the click and drag rectangle: http://jsfiddle.net/7uNfW/26/ but there is some problem that I can't figure out in function handleMouseDown(e) and function handleMouseUp(e)

Plus I need to get some ideas as to how will I go about selecting the SVG elements in the box.

Any help would be appreciated.

like image 206
user1340852 Avatar asked Sep 26 '13 18:09

user1340852


People also ask

How do you draw a rectangle in JavaScript?

The fillRect() is a method of the 2d drawing context object. The fillRect() method allows you to draw a filled rectangle at (x,y) position with a specified with and height on a canvas. In this syntax: x is the x-axis coordinate of the starting point of the rectangle.

How do you draw a rectangle mouse in canvas?

Draw a Rectangle on the HTML Canvas with a Mouse //... // window. addEventListener("mousedown", startDrawing); //... // window. addEventListener("mouseup", endDrawing); //... // window. addEventListener("mousemove", draw);


2 Answers

As for the creating of a Clink 'N Drag rectangle, I rewrote the code to become this. It looks like it's working just fine.

Now, for the SVG part, I'm not sure how you'd go about incorporating SVG into canvas. Have a look at this library instead: http://fabricjs.com/

For the task of detecting if your selection box is covering a SVG, I can give you the following suggestions:

  • Store the startX, startY, stopX, stopY as the mouse releases.
  • Loop through all SVG files
  • Check if there's a overlap, perhaps like so:

.

if ((svg.startY+svg.height) < startY) {
    return false; // svg too high

} else if (svg.y > stopY) {
    return false; // svg too low

} else if ((svg.x + svg.width) < startX) {
    return false;  // svg too far left

} else if (svg.x > stopX) {
    return false;  // svg too far right

} else {
    // Overlap
    return true;
}
like image 196
bvx89 Avatar answered Oct 03 '22 15:10

bvx89


In your fiddle you're referring to mouseUp. The jQuery method is referred to as mouseup. That's showing an error in the console.

Also, you're trying to update the html of an element that isn't in the DOM, #downlog.

Here's a fiddle showing something happening now: http://jsfiddle.net/7uNfW/33/

like image 25
Marty Cortez Avatar answered Oct 03 '22 14:10

Marty Cortez