Back

Draw a line between 2 elements

The goal is to find the position of the pink box (the element) relative to the orange box (the page).

The line element.getBoundingClientRect(); returns an object reporting the position of the element relative to the green box (the viewport).

Assume there is a canvas with position: absolute; top: 0; left:0; z-index: -1; which is the exact same size as the page. If there isn't just make one.

The function below will draw a line from the center of one element to the other.

  let c = document.getElementById('mycanvas');
  let ctx = c.getContext('2d');

  function drawLineBw2Els(c, ctx, el1, el2) {

    let cRect = c.getBoundingClientRect();
 
    // just think about these lines
    let rect1 = el1.getBoundingClientRect();
    let x1 = Math.abs(cRect.left) + (rect1.right + rect1.left)/2;
    let y1 = Math.abs(cRect.top) + (rect1.top + rect1.bottom)/2;

    let rect2 = el2.getBoundingClientRect();
    let x2 = Math.abs(cRect.left) + (rect2.right + rect2.left)/2;
    let y2 = Math.abs(cRect.top) + (rect2.top + rect2.bottom)/2;
  
    // orange
    ctx.strokeStyle = "#ffcc00";
 
    // draw a line
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
  
  }

And this should help the code above make sense.