Skip to content
Advertisement

Use a svg image to drag along a line in d3.js

I want to build a visualization in D3.js that illustrates the concept of potential energy and kinetic energy for my students. In essence, I want the students to be able to drag a skier up a slope (i.e. a Line) and when they drop him, he transits down again. I’m sure it is an easy task in D3 but I’m struggling to understand how I can get the skier icon to be draggable only along the line path?

Here’s an image for illustration:

enter image description here

I want the skier icon to switch place with the ball with the green connector. I have used https://observablehq.com/@mbostock/closest-point-on-line as inspiration for this project. Here, you can drag the circle up and down but the small ball will always be on that line. I want the same thing with my skier but I’m struggling to understand how I can accomplish this?

Here’s the fiddle.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You were very close! The only thing I did was draw two circles instead of three, and give the skier the coordinates of the last circle. Then I applied transform to the skier, because otherwise he would be anchored at the top left of the image, instead of the bottom centre.

I used datum instead of data, since datum only expects one value, while data expects an array. See this bl.ock for a good tutorial on it.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement