如何在CSS中使用背景图像无限平滑地平滑放大和缩小

时间:2019-06-30 17:54:47

标签: css

背景图像设置动画时不平滑(某种眨眼),我无法使其从图像中心缩放。

这是我要建立的个人网站。

    *{margin: 0;padding: 0;}

    body
    {
        background-color: #0C090A;
        background-image: url(../abstract-bg.png);
        animation: zoom 30s infinite;
            -webkit-animation: zoom 30s infinite;
    }

    @keyframes zoom {
        0% {
          background-size: 100%;
        }
        50% {
          background-size: 105%;
        }
        100% {
         background-size: 100%;
        }
      } 

我想让背景图像(1920 * 1080)缓慢缩放到原始大小的105%(或类似的大小),然后再回到100%。另外,如果可能,请使其从中心而不是左上角缩放。感谢那些能提供帮助的人。

2 个答案:

答案 0 :(得分:0)

是的,您当然可以:) 只需添加

  background-position:center center;
  background-repeat:no-repeat;

在体内的CSS 并添加

html{
  height: 100%;
}

完整的CSS代码:

* {
  margin: 0;
  padding: 0;
}
html {
  height: 100%;
}
body {
  background-color: #0C090A;
  background-image: url(https://images.pexels.com/photos/556416/pexels-photo-556416.jpeg);
  animation: zoom 30s infinite;
  -webkit-animation: zoom 30s infinite;

  background-position: center center;
  background-repeat: no-repeat;

}

@keyframes zoom {
  0% {
    background-size: 100%;

  }
  50% {
    background-size: 150%;
  }
  100% {
    background-size: 100%;
  }
}

您可以测试代码: https://playcode.io/358401

答案 1 :(得分:0)

这很不稳定,因为动画持续时间对于图像宽度5%来说太长。或者增加动画的大小或减少动画的持续时间,或者使用更大的图像。

或者您可以使用scale()来利用我相信的GPU,但是这次我们不会将图像用作背景。

body{
  overflow-x:hidden; 
}
img {
  transform-origin: center center;
  animation: zoom 30s infinite;
  max-width: 100%;
}

@keyframes zoom {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
    /* equals 105% */
  }
  100% {
    transform: scale(1);
  }
}
<img src="https://picsum.photos/id/238/1920/1080">

相关问题