Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!