简体   繁体   中英

How to connect dots in differents positions with svg?

I'm new at using svg as you can see and i have a problem connecting dots.

What I want to do is to connect this 2 dots with a line no matter their position.

As you can see in the image bellow when i change the cx="50" to cx="510" the line still in the same postion but i want the line to "follow" the second circle no matter the position.

Resuming:

In my case I have a static line what I want its to have a dinamic line that connects with the other dot when I change my coordinates(cx or cy).

在此处输入图片说明

  <!DOCTYPE html> <html> <head> <title></title> </head> <body> <svg width="1000" height="1000"> <circle id="circle0" cx="50" cy="50" r="20" stroke="black" stroke-width="3" fill="grey" onClick="dotClick(0)"></circle> <circle id="circle1" cx="50" cy="110" r="20" stroke="black" stroke-width="3" fill="grey" onClick="dotClick(1)"></circle> <line id="line0" x1="50" y1="50" x2="50" y2="100" /> </svg> <script> var buttons = {}; function dotClick(width) { (width === 0) ? buttons.one = !buttons.one : buttons.two = !buttons.two; document.getElementById("line0").setAttribute("stroke", (buttons.one && buttons.two) ? "red" : ""); document.getElementById("circle0").setAttribute("fill", (buttons.one ? "red" : "grey")); document.getElementById("circle1").setAttribute("fill", (buttons.two ? "red" : "grey")); } </script> </body> </html> 

To achieve expected change line x2 as well

<line id="line0" x1="50" y1="50" x2="510" y2="100" />

Codepen- https://codepen.io/nagasai/pen/NjabQJ

Updated codepen for dynamic line

https://codepen.io/nagasai/pen/OmxWLa?editors=1111

I can try to add a code example for you to illustrate what I mean but perhaps a textual explanation will suffice for now.

If you want the line to connect the two dots no matter where they may be, consider trying to pass the attributes in the circle elements to the line element. The first circle's cx and cy would correspond to the line's x1 and y1 and the second circle would be the x2 and y2 . (You can just as easily use getAttribute to grab this information off the circle elements)

How you get this information whether it be through an event.target you pass through the click handler or it be through how you're doing it now (simply grabbing the element by its id and shoving it in) doesn't truly matter. The point is no matter where these circles are, you want the circles to be supplying the information for the line coordinates and not hardcoded.

I hope this helps as a starting point. If you are still struggling, feel free to comment. You are really close but I'd really like to see you finish through :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM