Javascript帧动画加载闪烁

时间:2017-08-17 15:21:26

标签: javascript animation

这是动画的CodePen。它会在显示的帧的第一个周期闪烁。有没有办法阻止这种情况发生?

非常感谢任何帮助!



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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

这是因为第一次查看时需要加载图像。可以以不同方式预加载图像。 Here are three ways to preload images.

答案 1 :(得分:1)

如果您查看浏览器开发工具的网络选项卡,您会看到浏览器加载图片时会发生闪烁。

您应该在开始动画之前预加载所有图像,如下所示:

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>