2009-07-09 8 views
15

間の線Iは、n個<div> S <h1>タイトルと内の項目の<ul>リストと各を持っているを描画するキャンバスを使用しjQueryの - divを

私はキャンバスの上にこれらをフロートしたいと<div id="x"からの線を引きます。 >リスト項目yを<div id="z">にします。私は<divをドラッグ可能にするためにjQuery UIを使用しています。

キャンバス要素はページの途中にあります(テキストの段落とフォーム要素の前にあります)が、必要に応じて変更できます。

[編集]

私がグラフで質問をタグ付け

が、私は、このリンクを追加してみましょう。Graph_(mathematics) :-)

答えて

7

私は絶対にdiv要素のポジショニングを行い、その後、あなたがしたい場所にそれらを設定します。あなたは自分の位置を持っている場合は、

//Get the absolute position of a DOM object on a page 
function findPos(obj) { 
    var curLeft = curTop = 0; 
    if (obj.offsetParent) { 
     do { 
      curLeft += obj.offsetLeft; 
      curTop += obj.offsetTop; 
     } while (obj = obj.offsetParent); 
    } 
    return {x:curLeft, y:curTop}; 
} 

半分それらの幅/高さにそれを追加し、あなたがページ上の彼らの中心の位置を持っています。そして、この機能で自分の位置を取得します。今キャンバスの位置を見つけて、以前に見つかった数からそれを引く。これら2つの点の間に線を引くと、2つのdivをリンクするはずです。ケースでは、ここで私はそれをコーディングする方法をだ、明確ではありません。

var centerX = findPos(document.getElementById('x')); 
centerX.x += document.getElementById('x').style.width; 
centerX.y += document.getElementById('x').style.height; 
var centerZ = findPos(document.getElementById('Z')); 
centerZ.x += document.getElementById('z').style.width; 
centerZ.y += document.getElementById('z').style.height; 
//Now you've got both centers in reference to the page 
var canvasPos = findPos(document.getElementById('canvas')); 
centerX.x -= canvasPos.x; 
centerX.y -= canvasPos.y; 
centerZ.x -= canvasPos.x; 
centerZ.y -= canvasPos.y; 
//Now both points are in reference to the canvas 
var ctx = document.getElementById('canvas').getContext('2d'); 
ctx.beginPath(); 
ctx.moveTo(centerX.x, centerX.y); 
ctx.lineTo(centerZ.x, centerZ.y); 
ctx.stroke(); 
//Now you should have a line between both divs. You should call this code each time the position changes 

EDIT ところで、findPosを使用して、あなたも(で、ここで(比較的キャンバスにdiv要素の初期位置を設定することができます30; 40)):

var position = {x: 30, y: 40}; 
var canvasPos = findPos(document.getElementById('canvas')); 
var xPos = canvasPos.x + position.x; 
var yPos = canvasPos.y + position.y; 
document.getElementById('x').style.left = xPos+"px"; 
document.getElementById('x').style.top = yPos+"px";