-2

How would I connect 2 elements in a list with a curved line.

Here's an example using the SO sidebar:

enter image description here

I'm looking for an answer that's curved so that they don't look the same when going through each other, but they don't need to deliberately avoid each other. I think a good way to do it would be to calculate the curve based on the length of the line.

I think this should be pretty simple to do without using a library. Almost all the answers in the combined question involved some 600kbs of externals.

For example I like this answer: https://stackoverflow.com/a/35493737/663447 but I'm looking for a curved rather than a straight line.

Harry
  • 52,711
  • 71
  • 177
  • 261
  • 3
    Seems like this question is keep resurfacing and disappearing again. what's the story here? – Ulug Toprak Jan 16 '19 at 13:39
  • 2
    @UlugToprak I've certainly seen it once before. Last week, I believe. – VLAZ Jan 16 '19 at 13:45
  • @UlugToprak I posted it once before. The question was probably too confusing in earlier versions but harassing people to relook at the question even after changing it didn't seem like the right thing to do so I opted to repost it. If it needs improvement please leave some comments. Thanks in advance and sorry for the repost guys! – Harry Jan 16 '19 at 13:48
  • are those lines gonna be static or dynamically generated? – karoluS Jan 16 '19 at 13:49
  • @karoluS dynamically generated – Harry Jan 16 '19 at 13:50

1 Answers1

1

So this is what i came up with. I'm using a canvas to draw lines on it and getBoundingClientRect to get single elements position. It is using vanilla JS so no 600 kB dependencies.

https://codepen.io/kwiniarski97/pen/VqNjbm?editors=1111

var c = document.getElementById("canvas");
var li1 = document.getElementById("1");
var li1Pos = li1.getBoundingClientRect();
var li2 = document.getElementById("2");
var li2Pos = li2.getBoundingClientRect();
var li3 = document.getElementById("3");
var li3Pos = li3.getBoundingClientRect();
var li4 = document.getElementById("4");
var li4Pos = li4.getBoundingClientRect();
var ctx = c.getContext("2d");
drawLine(li1Pos, li4Pos, 30);
drawLine(li2Pos, li3Pos, 20);
function drawLine(from, to, deepness){
  ctx.beginPath();
  ctx.moveTo(from.x, from.y);
  ctx.bezierCurveTo(from.x + deepness, from.y , to.x+deepness, to.y, to.x, to.y);
  ctx.stroke();
}
div{
  display:flex;
}

canvas{
  margin-left: -45px;
}
<div>
<ul>
  <li id="1">1</li>
  <li id="2">2</li>
  <li id="3">3</li>
  <li id="4">4</li>
</ul>

<canvas id="canvas"></canvas>
</div>
karoluS
  • 2,980
  • 2
  • 23
  • 44