Home > Mobile >  Endless road animation CSS3
Endless road animation CSS3

Time:12-24

I have this 2D Highway background image https://opengameart.org/sites/default/files/background-1_0.png

I'm working on a mobile game (with JS and CSS3) of racing cars, and I want to make animation of this road to make an illusion of movement

Can someone please guide me what's the best practice for this case?

Currently I do something like that, but it's not smooth enough (especially in mobile browser) -

.main {
    background-image: url(https://opengameart.org/sites/default/files/background-1_0.png);
    background-repeat-x: no-repeat;
    background-size: 103%;
    background-repeat-y: repeat;
    background-position-y: 27px;
    animation: loopingRoad 0.1s infinite;
    height: 100%;
    width: 100%;
  }

@keyframes loopingRoad {
    100% {
      background-position-y: 1000%;
    }
    0% {
      background-position-y: 0%
    }
  } 

CodePudding user response:

Use

background-position: 0 0;
background-position: 0 -100000px;

as the keyFrame keys:

html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

.main {
    background-image: url(https://opengameart.org/sites/default/files/background-1_0.png);
    background-repeat-x: no-repeat;
    background-size: 103%;
    background-repeat-y: repeat;
    background-position-y: 27px;
    animation: loopingRoad 250s linear infinite;
    height: 100%;
    width: 100%;
    
    position: absolute;
    top: 0;
    left: 0;
}


@keyframes loopingRoad {
    from {
        background-position: 0 0;
    }
    to {
        background-position: 0 -100000px;
    }
}
<div  />

CodePudding user response:

Create a container in which you have the aspect ratio of the image set. This allows you to play with the width while keeping the image in the right proportions.

For the image itself. Make it twice the height of the container. This allows you to transform the entire road 50% upwards. When starting the animation, the top half of the road is exposed. At the end of the animation the bottom half is exposed. Loop this proces to create the illusion.

The transform property animates very well as it doesn't ask the browser to repaint the entire page, but only the element that is transformed.

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.view {
  max-width: 840px;
  height: auto;
  max-height: 100%;
  overflow: hidden;
}

.road-reel {
  width: 100%;
  height: auto;
  aspect-ratio: 840 / 650;
  overflow: hidden;
}

.road-image {
  background-image: url(https://opengameart.org/sites/default/files/background-1_0.png);
  background-repeat: repeat-y;
  background-size: auto 50%; /* Fit into 1 vertical half */
  animation: loopRoad 1.5s infinite linear both;
  height: 200%; /* Twice the height */
  width: 100%;
}

@keyframes loopRoad {
  from {
    transform: translate3d(0, 0%, 0);
  }
  to {
    transform: translate3d(0, -50%, 0);
  }
}
<div >
  <div >
    <div ></div>
  </div>
</div>

  • Related