1

I created a SVG file which consists of 35 different paths (train tracks). Now I want to split the paths/tracks into 16 segments so another SVG path (train) can move along it.

The goal in the end is that the user can determine which paths should be actived, i.e. the segments later on should be clickable by the user in sequence.

To test if it's working the train should randomly move along the tracks.

Currently I tried to assign the paths into segments like this:

const segments = {
    1: { x: document.getElementById("track1"), y: document.getElementById("track2")},
    2: { x: document.getElementById("track3"), y: document.getElementById("track4")},
    3: { x: ocument.getElementById("track5"),  y: document.getElementById("track6")},
...
};

This unfortunately is not working. I don't know why since I thought I could just assign the paths into the corresponding segments. Before the SVG file was a normally drawn PNG file in which the segments were manually assigned through their coordinates like this and it worked:

const segments = {
    1: { x: 1534, y: 534 },
    2: { x: 2278, y: 630 },
    3: { x: 2488, y: 1179 },
...
};

I'm new to coding in general, so I unfortunately don't know what to look for. The solutions I found were not exactly suited for my problem.

Thank you in advance for helping me.

Sunny
  • 11
  • 2
  • Is your SVG within an HTML file? Please show your HTML/SVG code. – Stuart Dec 15 '21 at 11:13
  • You need to get the coordinates of the track segments, either using `document.getElementById("track1").getBoundingClientRect().x` (which will return the coordinates of the top-left corner) or one of the methods [here](https://stackoverflow.com/a/6817703/567595) to get the path information. – Stuart Dec 15 '21 at 11:23

1 Answers1

0

document.getElementById("track1") will just return a path element. If you need the coordinates of the start of the path, you would need to do something like:

1: { x: document.getElementById("track1").getPointAtLength(0).x,
     y: document.getElementById("track1").getPointAtLength(0).y }
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181