Search code examples
javascriptanimationpaperjs

Animate polygon point on a circle with Paper.js


I need to animate a point (called segment in Paper.js) of a polygon, rotating it on a circle with origin in the original polygon point. See the image below:

enter image description here

I'm trying to do it with this code:

// Draw the polygon
var polygon = new Path.RegularPolygon({
    center: [100, 100],
    sides: 8,
    radius: 80,
});
// Animate
view.onFrame = function (event) {
    var offset = new Point(Math.cos(event.time*2), Math.sin(event.time*2));
    polygon.firstSegment.point = polygon.firstSegment.point.add(offset);
};

but I get two problems:

  • the origin of the circle is wrong
  • after some times of animation it starts to rotate in some strange and (apparently) randomly ways. It seems that it changes the circle origin

Here the whole code to see it in action:

https://codepen.io/anon/pen/xezQpb

Someone can helps? Thanks


Solution

  • The problem is that at each frame you refer to the position of the first segment which has moved a bit during the previous frame, so the offset sums up.

    Instead, just record the center at the beginning and offset from that point :

    var center = polygon.firstSegment.point.clone();
    [...]
    polygon.firstSegment.point = center.add(offset);
    

    https://codepen.io/anon/pen/YMjWBZ