javascript - 从 JavaScript Web Animations API 读取样式信息,中间状态
问题描述
给定一个网络动画,比如这里的那个:https ://codepen.io/arxpoetica/pen/aXqEwe
如何在任何给定时间点根据关键帧之间的状态获取 CSS 或样式信息?
示例代码:
<div class="thing"></div>
<style>
html {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background-color: #0a2933;
}
.thing {
height: 100px;
width: 100px;
background-color: orange;
}
</style>
<script>
document.querySelector('.thing').animate([
{ transform: 'rotate(0) scale(1)', backgroundColor: 'orange' },
{ transform: 'rotate(180deg) scale(3)', backgroundColor: 'blue' },
{ transform: 'rotate(360deg) scale(1)', backgroundColor: 'orange' }
], {
duration: 3000,
iterations: Infinity
})
</script>
注意:此 API 仅适用于有限的浏览器/平台。
解决方案
WAAPI方法.animate
返回Animation
对象,其中包括您需要的所有内容:
运行以下代码段:
var keyframes = [{
transform: 'rotate(0) scale(1)',
backgroundColor: 'orange'
},
{
transform: 'rotate(180deg) scale(3)',
backgroundColor: 'blue'
},
{
transform: 'rotate(360deg) scale(1)',
backgroundColor: 'orange'
}
];
var options = {
duration: 3000,
iterations: Infinity
};
var thing = document.querySelector('.thing');
var A = thing.animate(keyframes, options);
console.clear();
function getState() {
if (A.playState === 'running') {
document.querySelector('section').innerHTML += `<p>
progress: ${getProgress()*100|0}% <br>
transform: ${getComputedStyle(thing).transform} <br>
backgroundColor: ${getComputedStyle(thing).backgroundColor}
</p>`;
//A.startTime = 0;
A.pause();
} else {
A.play();
document.querySelector('section p:last-of-type').remove();
}
}
function getProgress() {
return A.effect ?
A.effect.getComputedTiming().progress :
A.currentTime % options.duration / options.duration
}
html {
height: 100%;
}
body {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
background-color: #0a2933;
}
section {
position: absolute;
z-index: 1;
top: 0;
left: 1em;
color: silver
}
.thing {
height: 100px;
width: 100px;
background-color: orange;
}
<!-- polyfill -->
<script src="https://rawgit.com/web-animations/web-animations-js/master/web-animations.min.js"></script>
<section>
<p>How do I get CSS or style information based on state between keyframes at any given point and time?</p>
<button onclick="getState()">Click here</button>
</section>
<div class="thing"></div>
此外,WAAPI 有一个不错的polyfill。
希望能帮助到你。
推荐阅读
- javascript - 无法从 prompt() 打开带有网站 URL 的窗口
- karate - 尝试利用“共享范围”来配置 ssl
- python - 将参数传递给在 AWS Fargate 上的 Docker 容器中运行的 Python
- redis - 当 redis 更新时,redis 会将更新发送到我的 grpc 服务器。如何实施
- node.js - Selenium Webdriver Donwload 文件路径(NodeJS)
- ios - iOS 变换和帧动画
- android - 无法将 android-layout 文件加载为 Sceneform 中的锚点
- tableau-api - 使用最后发生的事件创建维度
- c# - 在 Foreach 循环中检索特定 XML 节点的特定子节点
- spring-boot - Spring Boot web socket在第一次发送消息时出现问题