我想使用css关键帧动画制作一个css动画编辑器工具。
这个想法是有一个时间线来播放和预览 CSS 动画,并确定关键帧。
问题在于动画预览,我必须在两个关键帧之间的特定时间点插入 html 元素的样式。可以在js中计算简单的值(例如top位置号),但在某些情况下在js中插入一些css属性可能会很棘手(例如border-radius,如何插值从 “50% 20% 10% 10%” 到 “20% / 10%” ??? ) 的值
解决这个问题的一个想法是仅在特定关键帧处播放和解释 css 关键帧动画。
但仅播放特定范围的 CSS 动画似乎很复杂。我知道有
animation-range、animation-range-start 和 animation-range-end css 属性,但这些属性仍然是实验性的,似乎在我的场景中不起作用。
border-radius: 10% 30% 50% 70%; 和 border-radius: 10% / 50% 之间混合 css 边框半径样式值) ;?),而css方式比较复杂,很难用正确的方式解决。
这是我用CSS尝试过的
<head>
<style>
@keyframes colorAnim {
0% {
color: black;
}
50% {
color: red;
}
100% {
color: green;
}
}
.animated-element-with-offset {
animation: colorAnim 100ms infinite;
animation-play-state: paused;
}
</style>
</head>
<body>
<div class="animated-element-with-offset" id="some-element-you-want-to-animate">
Text Color Animation frame #50: Color expected is red
</div>
<button onclick="interpretAndPauseAnimation(50)">Interpret and Pause Animation at 50%</button>
<script>
const element = document.getElementById("some-element-you-want-to-animate");
let start, previousTimeStamp;
let duration = 100;
let endDuration = 49;
let done = false;
function step(timeStamp) {
if (start === undefined) {
start = timeStamp;
}
const elapsed = timeStamp - start;
if (previousTimeStamp !== timeStamp) {
if (elapsed > duration * (endDuration / 100)) {
done = true;
element.style.animationPlayState = 'paused';
} else {
element.style.animationPlayState = 'running';
}
}
if (elapsed < duration) {
// Stop the animation after 2 seconds
previousTimeStamp = timeStamp;
if (!done) {
window.requestAnimationFrame(step);
}
}
}
function interpretAndPauseAnimation(keyframePercentage) {
start = undefined;
previousTimeStamp = undefined;
done = false;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
</script>
</body>
</html>
@keyframes colorAnim {
0% {
color: black;
}
50% {
color: red;
}
100% {
color: green;
}
}
.animated-element-with-offset {
animation: colorAnim 100ms infinite paused;
/* you can easily set the below using JS */
animation-delay: -50ms; /* -1 * (50% of the duration) */
}
<div class="animated-element-with-offset" id="some-element-you-want-to-animate">
Text Color Animation frame #50: Color expected is red
</div>