0

So I've managed to find out how I can connect two DIV-elements with a straight line, see the code below, the blue line in the image. I would like to make the line a dangling line (red). Is it somehow possible to code this in Javascript?

thanks for the tips!

enter image description here

function connect(div1, div2, color, thickness) {
    var off1 = getOffset(div1);
    var off2 = getOffset(div2);
    var x1 = off1.left + (off1.width/2);
    var y1 = off1.top + off1.height + 2;
    var x2 = off2.left + (off2.width/2);
    var y2 = off2.top + 2;
    console.log (x1 + " " + x2);
    var length = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
    var cx = ((x1 + x2) / 2) - (length / 2);
    var cy = ((y1 + y2) / 2) - (thickness / 2);
    var angle = Math.atan2((y1-y2),(x1-x2))*(180/Math.PI);
    var htmlLine = "<div id=\"line\" style='padding:0px; margin:0px; height:" + thickness + "px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; width:" + length + "px; -moz-transform:rotate(" + angle + "deg); -webkit-transform:rotate(" + angle + "deg); -o-transform:rotate(" + angle + "deg); -ms-transform:rotate(" + angle + "deg); transform:rotate(" + angle + "deg);' />";
    document.body.innerHTML += htmlLine; 
}

function getOffset( el ) {
    var rect = el.getBoundingClientRect();
    return {
        left: rect.left + window.pageXOffset,
        top: rect.top + window.pageYOffset,
        width: rect.width || el.offsetWidth,
        height: rect.height || el.offsetHeight
    };
}

window.testIt = function() {
    var div1 = document.getElementById('div1');
    var div2 = document.getElementById('div2')
    connect(div1, div2, "#F00", 1); 
} 
JoostVanPoppel
  • 148
  • 1
  • 7
  • Does this answer your question? [Draw a curve with css](https://stackoverflow.com/questions/20803489/draw-a-curve-with-css) – Lajos Arpad Jun 17 '20 at 09:07
  • Thx @LajosArpad. I'm gonna dive into this. Just wondering if these lines can be drawn dynamically using Javascript. For example; when one of the two div-elements is dragged, how do I recalculate the position and re-shape the line... – JoostVanPoppel Jun 17 '20 at 09:21
  • Yes, you can do that. I would recommend the usage of either a canvas or svg. But since your question was about drawing lines between divs, I was not confident that you may be interested in a canvas-based solution. – Lajos Arpad Jun 17 '20 at 10:03

0 Answers0