简体   繁体   English

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

[英]How to smoothly change background (animate) in JavaScript?

I have 30 images that make together a full turn of a 3D model. 我有30张图像,它们构成了完整的3D模型。 I want to display the animation in browser. 我想在浏览器中显示动画。 I can not use CSS animation , which otherwise worked good. 我不能使用CSS animation ,否则效果很好。 The problem with JavaScript is flickering when the next image loads. 下一个图像加载时,JavaScript的问题会闪烁。 Is there any way to make it smoother? 有什么方法可以使它更平滑?

<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>

Perhaps you can use a supplemental image, load it, then bring it to the front using z-index. 也许您可以使用补充图像,加载它,然后使用z-index将其放到最前面。 Something like: 就像是:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM