首页 > 解决方案 > 如何将我的 animateMotion 与我的 CSS 动画同步?

问题描述

我没想到,目标是让正方形使路径消失。我的两个动画的持续时间都是 5 秒,但它们不相关。我是 svg 动画的新手,所以我还没有找到制作它的解决方案。

知道我该怎么做吗?

// Example class component
class Svg extends React.Component {
  render() {
    return (
        <div>
            <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" viewBox="0 0 500 500">
                <path className="path" id="motionPath" d="M404.88 470.22V79.69c-.2-19-14.21-33-17.52-36.19s-16.77-15.19-34.7-15.45h-1.11c-28.65.35-59.55-.12-319.52 0H28" stroke="#000" strokeWidth="4" stroke-miterlimit="10" fill="none"></path>
                <rect id="circle" x="-25" y="-25" rx="15" ry="15" width="50" height="50"></rect>

                <animateMotion id="forward"
                    xlinkHref="#circle"
                    dur="5s"
                    fill="freeze"
                    keyPoints="1;0"
                    keyTimes="0;1"
                    calcMode="linear">
                    <mpath xlinkHref="#motionPath"></mpath>
                </animateMotion>
            </svg>
        </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Svg />,
  document.getElementById("react")
);
.path {
        stroke-dasharray: 1000;
        stroke-dashoffset: 1000;
        animation: dash 5s linear reverse;
    }

    @keyframes dash {
        to {
            stroke-dashoffset: 0;
          }
      }
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

标签: cssanimationsvgcss-animationssvg-animate

解决方案


而不是使用一个 SMIL 和一个 CSS 动画同时执行 SMIL。

此外,当路径长度为 795.3 时,您正在为路径长度设置 1000 的动画

还有一个想法:您需要反转 css 动画,因为您的初始 stroke-dashoffset: 1000; 使用初始值 0 并将其设置为最大长度(在我的演示中为 795.3),现在您不需要再反转它了,

 <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" viewBox="0 0 500 500">
                <path class="path" id="motionPath" d="M404.88,470.22v-390.53c-0.2,-19,-14.21,-33,-17.52,-36.19s-16.77,-15.19,-34.7,-15.45h-1.11c-28.65,0.35,-59.55,-0.12,-319.52,0h-4.03" stroke="#000" stroke-width="4" stroke-miterlimit="10" fill="none" stroke-dasharray="795.30" stroke-dashoffset="0">
                  <animate
                    attributeName="stroke-dashoffset"
                    from="0" to="795.30"
                    dur="5s"
                    fill="freeze"
                    begin="0"/>
                </path>
                <rect id="circle" x="-25" y="-25" rx="15" ry="15" width="50" height="50">

                <animateMotion id="forward"
                    dur="5s"
                    fill="freeze"
                    keyPoints="1;0"
                    keyTimes="0;1"
                    calcMode="linear"
                    begin="0">
                    <mpath xlink:href="#motionPath"></mpath>
                </animateMotion>
                  
                  </rect>
</svg>


推荐阅读