jQuery - use canvas to draw lines between divs

后端 未结 1 1489
情深已故
情深已故 2020-12-24 15:09

I have n >s, each with > title and > list of items in.

I would like to float these over a canvas and draw l

相关标签:
1条回答
  • 2020-12-24 15:24

    I would make the div's positioning to absolute and then set them where you want. Then get their position with this function:

    //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};
    }
    

    When you have their position, add it to half their width/height, and you will have the position of their center on the page. Now find the position of the canvas and substract it from the previously found numbers. If you draw a line between those two points, it should link the two divs. In case it's not clear, here's how I would code it:

    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 By the way, using the findPos function you can also set the initial position of the divs relatively to the canvas (here at (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";
    
    0 讨论(0)
提交回复
热议问题