如何在JavaScript中平稳地更改背景(动画)?

时间:2018-09-24 11:25:07

标签: javascript css performance

我有30张图像,它们构成了完整的3D模型。我想在浏览器中显示动画。我不能使用CSS animation,否则效果很好。下一个图像加载时,JavaScript的问题会闪烁。有什么方法可以使它更平滑?

<div id="image" style="width: 1920px; height: 1080px;">
</div>
<script>
    let suffix;
    let i = 0;
    let image = document.getElementById("image");
    function setSuffix(){
        suffix = ("0" + (i+1)).slice(-2);
        i++;
        i = i % 30;
        image.style.background = "URL('" + suffix + ".jpg')";
    }
    setInterval(setSuffix, 1000);
</script>

1 个答案:

答案 0 :(得分:0)

也许您可以使用补充图像,将其加载,然后使用z-index将其置于最前面。像这样:

let suffix;
let i = 0;
let image1 = document.getElementById("image1");
let image2 = document.getElementById("image2");

// TIP: Remove these
let url1 = "https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-9/41667401_10155851253461762_5185170392754421760_n.png?_nc_cat=101&oh=beb534388a04dd5ea101bc9560fa5e24&oe=5C1F4FAD";
let url2 = "https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-9/34661720_10155632057856762_4698625317663670272_n.jpg?_nc_cat=106&oh=dd89a8d15e587dba4b7fe8b3ea38143e&oe=5C1E5CC0";

function setSuffix(){
  // TIP: Uncomment this
  //imageUrl = ("0" + (i+1)).slice(-2) + ".jpg";
  
  if (i % 2 === 0) {
    imageUrl = url1; // TIP: Remove this.
    image1.style.background = `URL('${imageUrl}')`;
    image1.style.zIndex = "1";
    image2.style.zIndex = "0";
  } else {
    imageUrl = url2; // TIP: Remove this.
    image2.style.background = `URL('${imageUrl}')`;
    image2.style.zIndex = "1"; 
    image1.style.zIndex = "0";
  }

  i++;
}
setInterval(setSuffix, 1000);
#image1, #image2{
  position:absolute;
  top: 0px;
  left: 0px;
}
<div id="image1" style="width: 1920px; height: 1080px;"></div>
<div id="image2" style="width: 1920px; height: 1080px;"></div>