解决方法
以下是如何使用线自动连接2个可拖动的画布矩形
首先,定义一些盒子和连接器:
// define any Boxes that will be drawn 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}); // define any connectors between any Boxes var connectors=[]; connectors.push({Box1:0,Box2:1});
绘制框并自动绘制连接器:
function draw(){ // clear the canvas ctx.clearRect(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(); } }
下面的代码允许拖动任何框并保持连接.
这是代码和小提琴:http://jsfiddle.net/m1erickson/GX6HS/
<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> body{ background-color: ivory; padding:20px;} #canvas{border:1px solid red;} </style> <script> $(function(){ 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,h:50}); var connectors=[]; connectors.push({Box1:0,Box2:1}); draw(); function draw(){ // clear the canvas ctx.clearRect(0,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").mousedown(function(e){handleMouseDown(e);}); $("#canvas").mousemove(function(e){handleMouseMove(e);}); $("#canvas").mouseup(function(e){handleMouseUp(e);}); $("#canvas").mouSEOut(function(e){handleMouSEOut(e);}); }); // end $(function(){}); </script> </head> <body> <p>Drag Boxes--they remain connected</p> <canvas id="canvas" width=300 height=300></canvas> </body> </html>