首页 > 解决方案 > SVG 路径动画与预期不符

问题描述

trajectory月球需要沿着与地球周围id 相同的路径移动。但它是随机移动的(好像在庆祝 4/20)。

请找到随附的代码。

.moon {
  offset-path: path('m159.39 54.867a71.83 20.37 0 0 1-71.83 20.37 71.83 20.37 0 0 1-71.83-20.37 71.83 20.37 0 0 1 71.83-20.37 71.83 20.37 0 0 1 71.83 20.37z');
  animation: revolve 10s 1s infinite ease-in-out forwards;
}

@keyframes revolve {
  from {
    offset-distance: 0%;
  }

  to {
    offset-distance: 100%;
  }
}
<svg width="169.31" height="115.66" viewBox="0 0 169.31 115.66">
  <circle cx="87.56" cy="54.867" r="45.855" fill="#ff4141" />
  <circle class="moon" cx="18.051" cy="54.867" r="8.092" fill="#ff9900" />
  <path
        id="trajectory"
        d="m18.051 54.867c1.9043-12.055 45.047-20.455 69.073-20.601 25.048-0.15208 64.422 2.9195 72.266 20.601-6.7091 16.516-45.54 20.472-69.791 20.552-24.814 0.082685-67.739-4.5793-71.548-20.552z"
        fill="none" stroke-width=".5px" stroke="#000000" />
</svg>

标签: htmlcsssvgcss-animations

解决方案


offset-path浏览器caniuse.com还不够支持

要实现月球沿轨迹移动,请考虑使用animateMotion

<svg width="169.31" height="115.66" viewBox="0 0 169.31 115.66">
  <circle cx="87.56" cy="54.867" r="45.855" fill="#ff4141" />
  <circle class="moon" cx="0" cy="0" r="8.092" fill="#ff9900" >
    <animateMotion begin="0s"
		 dur="12s" repeatCount="3"  fill="freeze" restart="whenNotActive" >>
	 <mpath xlink:href="#trajectory" />
	</animateMotion>
  </circle>
  <path
        id="trajectory"
        d="m18.051 54.867c1.9043-12.055 45.047-20.455 69.073-20.601 25.048-0.15208 64.422 2.9195 72.266 20.601-6.7091 16.516-45.54 20.472-69.791 20.552-24.814 0.082685-67.739-4.5793-71.548-20.552z"
        fill="none" stroke-width=".5px" stroke="#000000" />
		
</svg>


推荐阅读