Rotating globe in CSS

风格不统一 提交于 2019-11-28 02:54:53

In background-position: 500px 0px; replace 500px with 610px, which is the background-size

body {
  background-color: #111;
}
#earth {
  width: 300px;
  height: 300px;
  background: url(http://www.noirextreme.com/digital/Earth-Color4096.jpg);
  border-radius: 50%;
  background-size: 610px;
  box-shadow: inset 8px 36px 80px 36px rgb(0, 0, 0), inset -6px 0 12px 4px rgba(255, 255, 255, 0.3);
  animation-name: rotate;
  animation-duration: 12s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  -webkit-animation-name: rotate;
 -webkit-animation-duration: 12s;
 -webkit-animation-iteration-count: infinite;
 -webkit-animation-timing-function: linear;
}
@keyframes rotate {
  from {
    background-position: 0px 0px;
  }
  to {
    background-position: 610px 0px;
  }
}
@-webkit-keyframes rotate {
  from {
    background-position: 0px 0px;
  }
  to {
    background-position: 610px 0px;
  }
}
<div id="earth"></div>
Martijn

The problem in your code is that the imagesize (610px) and the animation's offset (500px) differ and at the reset of the animation it hops (110px).

A simple trick I like to use instead of defining the animation offset in pixel: Define it in percentages.
Instead of telling it to move 610px, I tell it to move 100%.

The bonus of the 100% method is that if you cange the picture, you dont have to alter all hardcoded values in your CSS, which, IMO, should be the prefered method.

Please note: It seems like moving from 0 to -100% creates a hop. Because we need the rotation to go in the right direction, I tried starting 100% and move it to 0, but at this point the image no longer exists.

@keyframes rotate {
   from { background-position:  100%  0; }
   to {   background-position:    0   0; }
}

Here is the snippet, but with 100% instead of a pixelvalue:
* Please note: The animation still hopped, but I can't test new code because the image no longer exists. The logic works, but this implementation seems not to. The following code is only a demo with the TS's code.

body {
  background-color: #111;
}
#earth {
  width: 300px;
  height: 300px;
  background: url(http://www.noirextreme.com/digital/Earth-Color4096.jpg);
  border-radius: 50%;
  background-size: 610px;
  box-shadow: inset 8px 36px 80px 36px rgb(0, 0, 0), inset -6px 0 12px 4px rgba(255, 255, 255, 0.3);
  animation-name: rotate;
  animation-duration: 12s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}
@keyframes rotate {
   from { background-position:  100%  0; }
   to {   background-position:    0   0; }
}
<div id="earth"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!