Reputation: 305
Let's assume I have two rectangles drawn on canvas. Those rects are draggable. Is there a possibility to create a line connected to those two shapes which would be not dragabble itself but it's position would change if position of one of the rects would change.
So for example I have shapes with a line between them and I move one of the shape but the line is also moving because it's still connecting those two shapes.
Upvotes: 0
Views: 2004
Reputation: 105035
Here's how to keep 2 draggable rectangles connected with a line.
Just draw a line from the center of one shape to the center of the other shape.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var dragTarget;
var boxes=[];
boxes.push({x:50,y:25,w:75,h:50}); // x,y,width,height
boxes.push({x:200,y:100,w:50,h:50});
var connectors=[];
connectors.push({box1:0,box2:1});
draw();
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
function draw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<boxes.length;i++){
var box=boxes[i];
ctx.fillRect(box.x,box.y,box.w,box.h);
}
for(var i=0;i<connectors.length;i++){
var connector=connectors[i];
var box1=boxes[connector.box1];
var box2=boxes[connector.box2];
ctx.beginPath();
ctx.moveTo(box1.x+box1.w/2,box1.y+box1.h/2);
ctx.lineTo(box2.x+box2.w/2,box2.y+box2.h/2);
ctx.stroke();
}
}
function hit(x,y){
for(var i=0;i<boxes.length;i++){
var box=boxes[i];
if(x>=box.x && x<=box.x+box.w && y>=box.y && y<=box.y+box.h){
dragTarget=box;
return(true);
}
}
return(false);
}
function handleMouseDown(e){
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
isDown=hit(startX,startY);
}
function handleMouseUp(e){
// Put your mouseup stuff here
dragTarget=null;
isDown=false;
}
function handleMouseOut(e){
handleMouseUp(e);
}
function handleMouseMove(e){
if(!isDown){return;}
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
dragTarget.x+=dx;
dragTarget.y+=dy;
draw();
}
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>Drag the rectangles</p>
<canvas id="canvas" width=300 height=300></canvas>
Upvotes: 1
Reputation: 3241
There is not a built-in way to do that with the HTML5 canvas.
However, you could write such a system manually. You would store the rectangles and line as JavaScript objects that knew how to render themselves on the canvas. Then, you would install a mouse event handler on the canvas.
Upvotes: 0