我有一个动画和 JS 用于交替 2 个 div 并更改它们的背景图像(来自几十个图像的数组),有点可互换的 div。一切正常,但是当动画运行时,我可以看到我的 CPU 是 100%。起初我认为这可能是由于 setInterval,但是当我将代码从交替图像更改为每次迭代增加一个数字并将其记录到控制台时 - 我看到 CPU 过载显着减少,大约 40-50%。所以我知道这可能是由于动画。
这是我的 HTML 代码:
<div class="wallpaper wallpaper-1" id="wallpaper-1"></div>
<div class="wallpaper wallpaper-2" id="wallpaper-2"></div>
CSS:
.wallpaper {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
-webkit-transform: translateZ(0);
-webkit-animation-timing-function: linear;
}
.animate {
-webkit-animation-name: fadeInOut;
-webkit-animation-duration: 6s;
}
@-webkit-keyframes fadeInOut {
0% {
opacity: 0;
-webkit-transform: scale(1);
}
16% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
-webkit-transform: scale(1.1);
}
}
和 JS 让一切都打勾:
Wallpapers.get().then(function(list) {
var wp1, wp2, divs = [], path, bgs = [], counterBgs = 0, bgsLength, currentId, doInterval;
wp1 = document.getElementById('wallpaper-1');
wp2 = document.getElementById('wallpaper-2');
divs = [ wp1, wp2 ];
path = 'assets/img/wallpapers/';
bgs = list.data;
bgsLength = bgs.length;
//Preload images
for(var i = 0; i < bgsLength-1; i++) {
var wp = new Image();
wp.src = path+list.data[i];
}
function manageBg() {
setInterval(function(){
doInterval();
}, 4000);
}
doInterval = function doInterval() {
currentId = counterBgs % bgsLength;
if (counterBgs % 2 === 0) {
wp1.style.backgroundImage = "url(" + path + bgs[currentId] + ")";
wp1.classList.add('animate');
wp1.style.zIndex = 1;
wp2.style.zIndex = 0;
setTimeout(function() {
wp1.classList.remove('animate');
}, 5950);
} else {
wp2.style.backgroundImage = "url(" + path + bgs[currentId] + ")";
wp2.classList.add('animate');
wp1.style.zIndex = 0;
wp2.style.zIndex = 1;
setTimeout(function() {
wp2.classList.remove('animate');
}, 5950);
}
counterBgs++;
};
doInterval();
manageBg();
});
任何想法如何减少 CPU 过载?