How about this: http://jsfiddle.net/4jqptynt/4/
Ok, first I did a little refactoring for your code to make things simpler. Itβs just things like putting code that gets the coordinates of the canvas into its own function, and caching some variables (like canvas context) in the outer area of ββthe function. Oh, and we define the dimensions of the rectangle as constants, because we will use the same numbers in several different places.
As you said, the first thing we need is to track existing rectangles using the rects array (easy enough to do in drawRectangle ). Then we need a function to check if some pair of coordinates is inside some rectangle:
function inRectangle(x, y) { for (var i = 0, l = rects.length; i < l; i++) { if ((x - rects[i].x) <= RECT_X && (y - rects[i].y) <= RECT_Y && (x - rects[i].x) >= 0 && (y - rects[i].y) >= 0) { return i; } } }
where RECT_X and RECT_Y define the sides of the rectangle. If the coordinates exist inside some rectangle, then this will return the index of this rectangle in the rects array.
Then this is the case of checking whether the rectangle happened or not, noting that the inRectangle will only return a number if the mousedown event was inside the rectangle:
$acanvas.on("mousedown", function (event) { var coords = getCoords(event), rect = inRectangle(coords.x, coords.y); if (typeof rect === "number") { dragStart = rect + 1; } else { drawRectangle(coords.x, coords.y); } });
if so, pay attention to which rectangle using dragStart , if you do not draw the rectangle as before.
Then, to complete the drag and drop, we need to bind the handler to mouseup :
$acanvas.on("mouseup", function (event) { if (!dragStart) { return; } var coords = getCoords(event), rect = inRectangle(coords.x, coords.y); if (typeof rect === "number") { drawConnection(dragStart - 1, rect); } dragStart = 0; });
If a drag has not been started, it does nothing. If the coordinates are not within the rectangle, then it does nothing but reset dragStart . If, however, it is inside the rectangle, then it draws a connecting line:
function drawConnection(rect1, rect2) { context.strokeStyle = "black"; context.lineWidth = 1; context.beginPath(); context.moveTo(rects[rect1].x + RECT_X/2, rects[rect1].y + RECT_Y/2); context.lineTo(rects[rect2].x + RECT_X/2, rects[rect2].y + RECT_Y/2); context.stroke(); context.closePath(); }