沿 html canvas 中的路径移动对象

Move object along path in html canvas

我有一条路径,我想在其中转一圈。

圆圈沿着路径完成移动后,它应该会消失。

对于圆圈的动画,我使用 canvas 中的 requestAnimationFrame() 方法。

要使用 CSS 沿路径设置 DOM 对象的动画,您需要了解 CSS 运动路径模块 - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Motion_Path

同样,要使对象沿 SVG 对象中的路径设置动画,您需要接受 SVG 元素 - https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateMotion

元素中实现类似的结果需要大量工作。您需要创建您的路径,然后随着时间的推移沿着该路径绘制坐标,然后在每个 RequestAnimationFrame 的适当坐标处绘制您的圆圈。这是可行的,尽管您可能希望借助 canvas and/or 动画库让您的生活更轻松。

  • GreenSock GSAP 有一个 MotionPath 插件,您应该可以使用它来获取沿路径的坐标,反过来,您可以使用它在 canvas 上绘制圆圈 - https://greensock.com/motionpath/

  • Scrawl-canvas [免责声明:我编写了这个库] 使沿着路径的动画尽可能简单。请参阅此 CodePen 以获取演示代码 - https://codepen.io/kaliedarik/pen/MWadEwm

    示例代码:

      scrawl.makePolyline({
          name: 'my-polyline',
          pins: [[10, 10], ['20%', '90%'], [120, 'center']],
          mapToPins: true,
          method: 'draw',
      });