Javascript框架动画加载闪烁
问题描述:
这是动画的CodePen。它在所显示帧的第一个周期闪烁。有没有办法阻止这种情况发生?Javascript框架动画加载闪烁
任何帮助将非常感谢!
let frames = [
"http://i.imgur.com/QhvQuaG.png",
"http://i.imgur.com/VjSpZfB.png",
"http://i.imgur.com/Ar1czX0.png",
"http://i.imgur.com/ROfhCv4.png",
"http://i.imgur.com/6B32vk7.png",
"http://i.imgur.com/2t5MWOL.png",
"http://i.imgur.com/a9wLBbc.png",
"http://i.imgur.com/OBKcW8f.png",
"http://i.imgur.com/RC6wLgw.png",
"http://i.imgur.com/2HyI8yS.png"];
let startframe = 0;
function arrow(){
let start = Date.now();
let timer = setInterval(function() {
let timePassed = Date.now() - start;
if (timePassed >= 20000) {
clearInterval(timer); // finish the animation after 2 seconds
return;
}
move();
}, 200);
}
function move(){
if (startframe==(frames.length-1)){
startframe=0;
} else {
startframe++;
}
// document.getElementById('continue').style.backgroundSize = "100%";
document.getElementById('continue').style.background = "url(" + frames[startframe] +")";
document.getElementById('continue').style.backgroundSize = "100%";
}
#continue {
width: 80px;
height:40px;
}
<div onclick = "arrow()">Start</div>
<div id="continue"></div>
答
如果您查看浏览器开发工具的网络选项卡,您会看到当浏览器加载图像时发生闪烁。
你应该开始动画之前预装的所有图像,像这样:
let frames = [
"http://i.imgur.com/QhvQuaG.png",
"http://i.imgur.com/VjSpZfB.png",
"http://i.imgur.com/Ar1czX0.png",
"http://i.imgur.com/ROfhCv4.png",
"http://i.imgur.com/6B32vk7.png",
"http://i.imgur.com/2t5MWOL.png",
"http://i.imgur.com/a9wLBbc.png",
"http://i.imgur.com/OBKcW8f.png",
"http://i.imgur.com/RC6wLgw.png",
"http://i.imgur.com/2HyI8yS.png"
]
var startframe = 0
var images = [] // This array will contain all the downloaded images
function preloadImages() {
var loaded = 0
for (i = 0; i < frames.length; i++) {
images[i] = new Image();
images[i].onload = function() {
loaded += 1
if (loaded >= frames.length) {
arrow()
}
}
images[i].src = frames[i]
}
}
function arrow(){
let start = Date.now();
let timer = setInterval(function() {
let timePassed = Date.now() - start;
if (timePassed >= 20000) {
clearInterval(timer) // finish the animation after 2 seconds
return;
}
move()
}, 200)
}
function move() {
var c = document.getElementById('continue')
c.innerHTML = '' // remove the content of #continue
// Insert the already exiting image from the images array
// into the container instead of downloading again with css
c.append(images[startframe])
if (startframe >= frames.length - 1) {
startframe = 0
}
else {
startframe++
}
}
#continue {
width: 80px;
height:40px;
}
#continue > img {
max-width: 100%;
}
<div onclick = "preloadImages()">Start</div>
<div id="continue"></div>
在哪里联系? – Ikbel
@ikbel谢谢! – Lana
没问题,查看下面的答案。 – Ikbel