我可以将 animate() 用于 SVG <path> 吗?

Can i use animate() for SVG <path>?

正在尝试使用 vanila animate() 函数为 SVG 元素设置动画

路径:

<path id="path1" fill="black" d="M30,30l 50,10 0,50"></path>

Js:

path1.animate([
    { d: `M30,30 l10,10 50,0` },
    { d: `M30,30 l60,10 50,20` },
    { d: `M30,30 l10,10 50,0` },
 ], {
    duration: 1000
})

收到警告并none 工作:

属性d 的关键帧值无效:M30,30 l10,10 50,0 属性 d 的无效关键帧值:M30,30 l60,10 50,20 属性 d 的关键帧值无效:M30,30 l10,10 50,0

js animate() 正在使用 Web Animation API.
因此,您需要将 d 坐标包装在 path() 函数中,就像在 css 路径动画中一样。

path.animate([
    { d: "path('M40 40 l10 10 50 0')" },
 ], {
    duration: 1000,
})

let path0 = document.getElementById("path0");

path0.animate([
   // { d: "path('M30,30l 50,10 0,50')" },
    { d: "path('M40 40 l10 10 50 0')" },
    { d: "path('M50,50 l60,10 50,20')"},
    { d: "path('M30,60 l10,20 50,0')" },
 ], {
    duration: 1000,
    iterations: Infinity
})
svg {
  width: 200px;
  display: inline-block;
  border: 1px solid red;
}

.pathAni {
  transition: 0.3s;
}

.pathAniCss {
  animation: dAni 3s forwards infinite;
}

@keyframes dAni {
  33% {
    d: path("M40 40 l10 10 50 0");
  }
  66% {
    d: path("M50,50 l60,10 50,20");
  }
  100% {
    d: path("M30,60 l10,20 50,0");
  }
}
<svg viewBox="0 0 100 100">
  <path class="pathAn0" id="path0" fill="black" d="M30,30l 50,10 0,50"></path>
</svg>

<svg viewBox="0 0 100 100">
  <path class="pathAniCss" id="path2" fill="black" d="M30,30l 50,10 0,50"></path>
</svg>

来自 W3C 文档:网络动画; W3C 工作草案,2021 年 5 月 18 日

The Web Animations model is intended to provide the features necessary for expressing CSS Transitions [CSS-TRANSITIONS-1], CSS Animations [CSS-ANIMATIONS-1], and SVG [SVG11]. As such, the use cases of Web Animations model is the union of use cases for those three specifications.

Check browser support for path()
Firefox caniuse 报告 2022:

Only supported on the clip-path and offset-path properties.

一些测试浏览器支持的例子:Animate SVG Path Changes in CSS