Javascript jQuery-使用画布在div之间绘制线

Javascript jQuery-使用画布在div之间绘制线,javascript,jquery,graph,canvas,Javascript,Jquery,Graph,Canvas,我有n个s,每个都有标题和项目列表 我想把它们漂浮在画布上,从列表项y到绘制线条。我正在使用jqueryui使s可拖动 canvas元素位于页面的一部分(一段文本和它前面的一些表单元素),但如果需要,我可以更改它 [编辑] 我用图表标记了这个问题,但让我添加以下链接::-)我会将div的位置设置为绝对位置,然后将它们设置在您想要的位置。然后使用此函数获取其位置: //Get the absolute position of a DOM object on a page function find

我有n个
s,每个都有
标题和
项目列表

我想把它们漂浮在画布上,从
列表项y到
绘制线条。我正在使用jqueryui使
s可拖动

canvas元素位于页面的一部分(一段文本和它前面的一些表单元素),但如果需要,我可以更改它

[编辑]


我用图表标记了这个问题,但让我添加以下链接::-)

我会将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";