Home > Blockchain >  SVG connect two points with a line, and automatically update the line if a point is moved
SVG connect two points with a line, and automatically update the line if a point is moved

Time:04-02

I'd like to connect two points (circles) with a line:

window.onclick = () => {
    document.getElementById('c2').setAttribute("cx", 150);
}
<svg>
  <circle cx="10" cy="10" r="2" id="c1" />
  <circle cx="90" cy="50" r="2" id="c2" />
  <line x1="10" y1="10" x2="90" y2="50" stroke="black" />
</svg><br>
Click here to move a circle.

such that if I modify the center of any <circle> with setAttribute("cx", 150) then the line automatically follows the new circle position.

Is there a way to do this with <use>? Something like (pseudo-code):

<svg>
  <circle cx="10" cy="10" r="2" id="c1" />
  <circle cx="90" cy="50" r="2" id="c2" />
  <use x1=xlink:c1:cx y1=xlink:c1:cy x2=xlink:c2:cx y2=xlink:c2:cy stroke="black" type="line" />
</svg>

Goal: I don't want to have to set the coordinates two times, in both the circle and line. Instead I would like to set the coordinates once, and that the line uses a reference to the circle elements.

Note: I have read SVG connect two points with a line but it did not help.

CodePudding user response:

You can use a <marker> that can be placed on start, middle and end of an element.

window.onclick = () => {
    document.getElementById('l1').setAttribute("x2", 150);
}
<svg viewBox="0 0 200 100" width="200">
  <defs>
    <marker id="circle" viewBox="0 0 4 4" refX="2"
      refY="2" markerWidth="4" markerHeight="4">
      <circle cx="2" cy="2" r="2" />
    </marker>
  </defs>
  <line id="l1" x1="10" y1="10" x2="90" y2="50" stroke="black"
    marker-start="url(#circle)" marker-end="url(#circle)"/>
</svg><br>
Click here to move a circle.

  • Related