Search code examples
javascriptsvganime.js

How to get points along motion path in anime.js


I am making an animation along an SVG path with anime.js.

I have copied the example from here and everything is working fine.

I would like to be able to get all the x and y points along the tweened path, at once (ie on init of my script, not one one as it tweens) to use to make a static shape, but I don't know where to begin. I have looked at the source code but am unsure if there is a function available for this.

I understand there would be more or less points depending on the duration of the tween. With a standard tween, say moving from 0 - 250 I can imagine how I could just count between the from and the to but because a path does not simply increment, rather it rises and falls, I don't know I would go about getting the points.

Apologies if this question is not clear, I hope I have articulated what I'm after but if you need any more info to advise, please ask.

Thanks


Solution

  • <path> elements have a couple of methods that you should find useful.

    • getPointAtLength(length) Gets the X,Y coordinates of a point length along the path
    • getTotalLength() Gets the total length of the path

    An example of typical usage:

    var  mypath = document.getElementById("mypath");
    var  pathLength = mypath.getTotalLength();
    var  pt = mypath.getPointAtLength(pathLength / 2);  // halfway along the path
    console.log("x="+pt.x+" y="+pt.y);