我有以下功能,通過在每個“刻度”處調整它們的樣式,將某些元素“向上”滾動到視圖之外:
const incr = 1;
let moved = 0;
function changeHeight( children, duration, setTop) {
// duration = 1500
const height = children.clientHeight; // in this case, 166px
let moved = 0;
const slideUp = function (timestamp) {
// we're done if the amount moved is larger than height
if ( moved < height ) {
children.style.top = `${ setTop( moved, height ) }px`;
moved = moved incr // move by some amount
requestAnimationFrame(slideUp)
} else {
// reset
moved = 0;
}
};
// start sliding
slideUp();
}
如果requestAnimationFrame大約每 16 毫秒觸發一次,我想用它duration來指示影片將運行多長時間,所以公式似乎是height * 16.5 / duration
我很困惑requestAnimationFrame- 為什么每個滴答的時間不是恒定的?我想使用timestamp由以下生成的,requestAnimationFrame但前幾個周期花費的時間比 ~16.5 的平均值長得多
16.5 在不同的機器或螢屏上看起來會不同嗎?
如何使高度變化完全符合指定的時間量?
uj5u.com熱心網友回復:
您想要的稱為增量時間。公式是Math.min((now - start) / duration, 1) * final_amount。
使用此增量時間,您無需關心間隔觸發的頻率,每一步都呈現為“應在的位置”。
至于你的問題,
為什么每個滴答的時間不是恒定的
當然是因為瀏覽器在第一幀中有很多事情要做,而不能在 16.7ms 幀中做所有事情。因此,它會將您的回呼移動到稍后執行,如果壓力太大,甚至可能會跳幀。
16.5 在不同的機器或螢屏上看起來會不同嗎?
是的,requestAnimationFrame基本上會嘗試跟隨顯示幕的重繪 率。所以在 60Hz 顯示幕上你確實每幀有 16.7ms,但在 120Hz 顯示幕上你只有一半。
如何使高度變化完全符合指定的時間量?
使用增量時間:
const elem = document.querySelector("div");
let moved = 0;
changeHeight(elem, 200, 5000);
function changeHeight(elem, height, duration) {
const start = performance.now();
const step = function () {
const now = performance.now();
const delta = Math.min((now - start) / duration, 1);
elem.style.height = (delta * height) "px";
if (delta < 1) {
requestAnimationFrame(step);
}
};
step();
}
div { width: 50px; background: green; }
<div></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/376231.html
標籤:javascript 动画片 请求动画帧
下一篇:減慢引導程式微調器的速度
