【问题标题】:Changing background after downloading the image-- best method?下载图像后更改背景 - 最好的方法?
【发布时间】:2021-07-25 22:58:57
【问题描述】:

我正在制作一个天气应用程序,我想根据天气更改背景图像。我试图让它顺利过渡,但我遇到的问题是第一次下载图像时,过渡(通常)不会发生,大概是因为图像的下载时间比实际效果更改要长.例如,如果我看到一个多云的城市,最初的变化是突然的。但是如果之后我得到另一个多云的城市,或者回到同一个城市,多云的图像会平稳过渡。

我这样做的方式是在 javascript 中说,如果我的 api 响应告诉我它的阴天,我在 JavaScript 中将 body 的属性设置为“阴天”。在 css 中,如果数据集是“多云”,我将背景设置为多云图像。例如:

 if(icon == "03d" || icon == "03n"){body.dataset.weather = "scattered-clouds"}

然后在css中:

body[data-weather ="scattered-clouds"]::before{
    content: ' ';
    position: fixed; 
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: gray;
    background: url('img/clouds/pexels-chris-kane-166360.jpg') no-repeat center center;
    background-size: cover;
    will-change: transform; 
    z-index: -1; 
    transition: 1.5s all ease;     
}

我可以预先下载所有图像,但这似乎是一种不好的做法,而且浪费数据。有没有更标准的方法来做到这一点?

【问题讨论】:

  • “我正在努力让它顺利过渡”?预加载所有图像不是一个好主意,是的。现在,这一切都取决于您想要达到的效果。我的建议是:淡出当前天气图像,加载新图像并淡入。
  • 当然,但这就是我的问题的重点——如何先加载新图像并将其淡入?

标签: javascript css image download


【解决方案1】:

使用 Image() API MDN reference

    setTimeout(() => {
        const image = document.querySelector(".image");
        const img = new Image(); 
        img.onload = () => {
            image.src = img.src
            image.style.animation = "fadeIn 1s ease";
        };
        img.src = 'https://images.unsplash.com/photo-1627156863760-f49b81d8ab77?fm=jpg&w=1950&fit=max';
    }, 2000);
    @keyframes fadeIn {
        0% {
            opacity: 0;
        }

        100% {
            opacity: 1;
        }
    }
    .image-wrapper {
        width: 80vw;
        height: 80vh;
    }

    .image-wrapper img {
        width: 100%;
        height: 100%;
     }
    
<div class="image-wrapper">
    <img class="image"
        src="https://images.unsplash.com/photo-1534430480872-3498386e7856?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&fit=max&w=1950">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-17
    • 2022-06-12
    • 1970-01-01
    • 2015-11-11
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多