我有n <div
&gt; s,每个都有<h1
&gt;标题和<ul
&gt; 。中的项目列表。
我想将它们放在画布上并从<div id="x"
&gt;中绘制线条。列表项y到<div id="z"
&gt;。我正在使用jQuery UI来使<div
&gt; s可拖动。
canvas元素位于页面的下方(文本段落和一些表单元素位于其前面)但是如果需要,我可以更改它。
[编辑]
我用图表标记了问题,但是让我添加此链接:Graph_(mathematics): - )
答案 0 :(得分: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};
}
当你有他们的位置时,将它加到他们的宽度/高度的一半,你将在页面上找到他们的中心位置。现在找到画布的位置,并从先前找到的数字中减去它。如果你在这两个点之间画一条线,它应该链接两个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
修改强> 顺便说一句,使用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";