【问题标题】:Draw a dashed path using Framer Motion in React在 React 中使用 Framer Motion 绘制虚线路径
【发布时间】:2022-01-26 03:32:47
【问题描述】:

我正在尝试使用 Framer Motion 绘制虚线路径,或者至少给出这种错觉。想想在藏宝图上为人行道设置动画。动画路径长度似乎是一种常见的方法,所以我已经实现了它,如下所示。

<motion.span
     initial={{ pathLength: 0 }}
     animate={{ pathLength: 1 }}
     d="...a list of coordinates"
     stroke="#000"
     strokeWidth="5"
     strokeDasharray="8"
/>

但似乎动画路径长度不适用于 strokeDasharray。当我使用该属性添加 strokeDasharray 值时,路径长度会设置动画,但 strokeDasharray 值在检查时读取为 2000 像素而不是 8 像素。当我使用 CSS 或内联样式添加 strokeDasharray 时,路径正确虚线,但动画不起作用。

根据我的阅读,strokeDasharray 在计算时使用了路径长度,所以我猜测初始的“0”值是把事情搞砸了。可能差远了我不知道。

这里有一个简单的解决方法吗?或者我应该重新评估我如何制作动画?谢谢!

【问题讨论】:

    标签: reactjs svg framer-motion


    【解决方案1】:

    不是使用 Framer Motion 的解决方案,但发现 Ruskinz 的这支笔使用一些 css 动画来完成这项工作。 HTML 如下所示:

    <svg xmlns:xlink="http://www.w3.org/1999/xlink" width="340" height="333" viewBox="0 0 340 333">
      <defs>
        <path id="path1" d="M66.039,133.545c0,0-21-57,18-67s49-4,65,8s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41 C46.039,146.545,53.039,128.545,66.039,133.545z" />
        <mask id="mask1"><use class="mask" xlink:href="#path1"></mask>
      </defs>
      <use class="paths" xlink:href="#path1" mask="url(#mask1)" />
    </svg>
    

    CSS 看起来像这样:

    .paths {
      fill: none;
      stroke: grey;
      stroke-dasharray: 5;
      stroke-width: 5;
      stroke-linejoin: round;
    }
    
    .mask {
      fill: none;
      stroke: white;
      stroke-width: 10;
      stroke-dasharray: 1000;
      stroke-dashoffset: 1000;
      animation: dash 5s linear alternate infinite;
    }
    
    /* does not work in IE, need JS to animate there */
    @keyframes dash {
      from {
        stroke-dashoffset: 1000;
      }
      to {
        stroke-dashoffset: 0;
      }
    }
    

    https://codepen.io/elliz/pen/prYqwx查看完整的笔

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2022-01-11
    • 2021-06-29
    • 2020-12-18
    • 1970-01-01
    • 2012-04-28
    • 2021-03-02
    • 2020-12-28
    • 2021-09-14
    • 2019-12-31
    相关资源
    最近更新 更多