我的网站上有一个简单的JS动画。它对#frame1
中包含的一堆照片进行动画处理,然后无限期地在屏幕上循环。 #frame1
实际上是1920x1080的区域,始终是旋转的照片显示。
Chrome中的内存占用量一直在增长。它以这种速度(50
)增长得很快,而以100增长得慢。这似乎是由于要移动大量像素。有什么方法可以提高此应用程序的内存性能,而又不降低间隔的速度?
function start_scroll() {
var elem1 = document.getElementById("frame1");
var pos1 = 0; // Starting position of box1.
var id = setInterval(frame, 50); // Set speed here.
function frame() {
if (pos1 == frameheight * -1) { // If it just disappeared, move it to the bottom and populate it with the next series of pics.
pos1 = frameheight;
populate(1); // Populate the first frame with the next set of pics.
} else { // Otherwise, keep on moving up.
pos1--;
elem1.style.top = pos1 + 'px';
}
}
}
最佳答案
将setInterval()
替换为requestAnimationFrame()
。这样可以有效地使动画与监视器更新同步。
function start_scroll() {
var elem1 = document.getElementById("frame1");
var pos1 = 0;
//var id = setInterval(frame, 50); // don't use setInterval
requestAnimationFrame(frame); // start once, using rAF
function frame() {
if (pos1 == frameheight * -1) {
pos1 = frameheight;
populate(1);the next set of pics.
} else {
pos1--;
elem1.style.top = pos1 + 'px';
}
requestAnimationFrame(frame); // loop using rAF
}
}
可以使用
cancelAnimationFrame(timeRef)
或标志来停止动画。var timeRef;
循环内:
timeRef = requestAnimationFrame(frame); // loop using rAF
典型的帧速率为每秒60帧。在某些高端显示器上也许更多。您可以使用提供的时间戳进行调整。
function loop(timestamp) {
// compare time here
requestAnimationFrame(loop); // loop
}
requestAnimationFrame(loop); // start
关于javascript - 使用Javascript更有效地对图像进行动画处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37902517/