div和div之间画横线_jQuery - 使用canvas在div之间绘制线条

鄂和璧
2023-12-01

dutchflyboy..

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

 类似资料: