【发布时间】:2021-05-08 15:06:00
【问题描述】:
我想用 CSS var 为 SVG 圆的属性 stroke-dasharray 设置动画。
绿色表示动画正确且动画连续流畅。
红色表示动画不正确,因为它分步进行。
我认为计算的 CSS 变量有问题,但我不明白是什么。
我们可以看到带有正方形的动画是正确的,即使它使用了计算出的 CSS var。
body {
display: flex;
}
svg {
width: 200px;
height: 200px;
}
circle.good {
stroke: green;
stroke-width: 5;
animation: good-dash 2s ease-in-out infinite;
}
circle.bad {
stroke: red;
stroke-width: 5;
animation: bad-dash 2s ease-in-out infinite;
--stroke-dasharray: 10;
}
.square {
width: 200px;
height: 200px;
background-color: green;
animation: good-roll 2s infinite ease-in-out both;
position: relative;
--left: 1;
}
@keyframes good-dash {
0% {
stroke-dasharray: 1, 10;
}
50% {
stroke-dasharray: 1, 5;
}
100% {
stroke-dasharray: 1, 10;
}
}
@keyframes bad-dash {
0% {
stroke-dasharray: 1, var(--stroke-dasharray);
}
50% {
stroke-dasharray: 1, calc(var(--stroke-dasharray) / 2);
}
100% {
stroke-dasharray: 1, var(--stroke-dasharray);
}
}
@keyframes good-roll {
0% {
left: calc(var(--left) * 1px);
}
50% {
left: calc(var(--left) * 50px);
}
100% {
left: calc(var(--left) * 1px);
}
}
<svg viewBox="25 25 50 50">
<circle class="good" cx="50" cy="50" r="20" fill="none"/>
</svg>
<svg viewBox="25 25 50 50">
<circle class="bad" cx="50" cy="50" r="20" fill="none"/>
</svg>
<div class="square"></div>
【问题讨论】:
-
在什么浏览器中?
-
@TemaniAfif 问题中写的内容不应该在任何浏览器中工作。它可能在 Chrome 中执行,因为它似乎有一个非标准的 calc 实现。 Safari、Firefox 和 w3c 更严格。
标签: css svg css-animations svg-animate css-variables