gpt4 book ai didi

javascript - 我可以对 SVG 使用 animate() 吗?

转载 作者:行者123 更新时间:2023-12-03 08:11:21 25 4
gpt4 key购买 nike

尝试使用 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
})

收到警告但没有任何效果:

属性 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 necessaryfor expressing CSS Transitions [CSS-TRANSITIONS-1], CSS Animations[CSS-ANIMATIONS-1], and SVG [SVG11]. As such, the use cases of WebAnimations model is the union of use cases for those threespecifications.

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

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

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

关于javascript - 我可以对 SVG <path> 使用 animate() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70730817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com