jQuery - 使用canvas在div之间绘制线条

15

我有n个

元素,每个元素都有

标题和
    列表。

    我想把它们浮动到画布上,并从id为"x"的

    元素的列表项y绘制到id为"z"的
    元素。我正在使用jQuery UI使
    元素可拖动。

    画布元素在页面中部(文本段落和一些表单元素在其之前),但如果需要,我可以更改位置。

    [编辑]

    我标记了这个问题的图形,但让我添加这个链接:Graph_(mathematics) :-)

1个回答

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";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接