【问题标题】:Looping parallax effect on full-width element keeps jumping in CSS / JS全角元素的循环视差效果在CSS / JS中不断跳跃
【发布时间】:2020-04-06 11:11:45
【问题描述】:

我最喜欢的最终目标是拥有一个性能友好的背景,可以流畅地循环而不会跳跃。我在网上找到的所有资源要么对性能不太友好,要么只适用于具有固定宽度的元素。

目前一切看起来都还不错,但背景在不同屏幕上的缩放比例很差,并且偶尔会出现较大的跳跃。我认为跳跃是由于元素翻译中的错误,但我还没有看到一个好的解决方案。将元素的宽度设置为 200% 并将它们转换为 -50% 以上似乎是一个 hacky 解决方案,我觉得应该有更好的方法。

我更希望找到一个全 CSS 的解决方案,但如果没有其他可行的方法,诉诸 JS 就可以了。

小提琴:https://jsfiddle.net/r4fz0Lot/3/

代码:

* { box-sizing: border-box; }
html, body, #container { width: 100%; height: 100%; }
body { margin: 0; }

#container {
  background-color: rgba(0, 0, 0, 0.9);
  image-rendering: pixelated;
  overflow: hidden;
  position: fixed;
}

#stars {
  background: url('https://i.imgur.com/Ym03Zkf.png') repeat 0 0;
  animation: loop 25s linear infinite;
  z-index: 1;
}

#mountains {
  background: url('https://i.imgur.com/jfef1r3.png') repeat-x 0 bottom;
  animation: loop 20s linear infinite;
  z-index: 2;
}

#ground {
  background: url('https://i.imgur.com/P13CzUo.png') repeat-x 0 bottom;
  animation: loop 15s linear infinite;
  z-index: 3;
}

#stars, #mountains, #ground {
  width: 200%; height: 100%;
  background-size: 30%;
  bottom: 0; left: 0;
  position: fixed;
}

@keyframes loop {
  from { transform: translateX(0); }
  to { transform: translateX(-50%); }
}
<div id="container">
  <div id="ground"></div>
  <div id="mountains"></div>
  <div id="stars"></div>
</div>

【问题讨论】:

标签: javascript html css loops parallax


【解决方案1】:

您将background-size 设置为 30%,因此您需要翻译 30% 的一些倍数来翻译“一个图像单元”

* { box-sizing: border-box; }
html, body, #container { width: 100%; height: 100%; }
body { margin: 0; }

#container {
  background-color: rgba(0, 0, 0, 0.9);
  image-rendering: pixelated;
  overflow: hidden;
  position: fixed;
}

#stars {
  background: url('https://i.imgur.com/Ym03Zkf.png') repeat 0 0;
  animation: loop 8s linear infinite;
  z-index: 1;
}

#mountains {
  background: url('https://i.imgur.com/jfef1r3.png') repeat-x 0 bottom;
  animation: loop 6s linear infinite;
  z-index: 2;
}

#ground {
  background: url('https://i.imgur.com/P13CzUo.png') repeat-x 0 bottom;
  animation: loop 5s linear infinite;
  z-index: 3;
}

#stars, #mountains, #ground {
  width: 200%; height: 100%;
  background-size: 30%;
  bottom: 0; left: 0;
  position: fixed;
}

@keyframes loop {
  from { transform: translateX(0); }
  to { transform: translateX(-30%); }
}
<div id="container">
  <div id="ground"></div>
  <div id="mountains"></div>
  <div id="stars"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2018-12-24
    相关资源
    最近更新 更多