SVG 用一条线连接两点,如果点移动则自动更新线

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

我想用一条线连接两点(圆):

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.

这样,如果我用 setAttribute("cx", 150) 修改任何 <circle> 的中心,那么直线 会自动跟随新的圆圈位置 .

有没有办法用 <use> 做到这一点?类似于(伪代码):

<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>

目标:我不想在 circleline 中设置两次坐标。相反,我想设置一次坐标,并且 line 使用对 circle 元素的引用。

注意:我已阅读 SVG connect two points with a line 但没有帮助。

您可以使用 <marker> 可以放置在元素的开头、中间和结尾。

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.