Liz Banach Liz Banach - 9 days ago 5
Javascript Question

Car driving forward animation using JavaScript/CSS3 for banner advertisement

Is there a way to use JavaScript or CSS3 to animate an image of a car driving towards a user? To clarify, the car image should animate from the background, with the image smaller and seemingly further away and gradually get larger as it "drives" forward to the foreground of the image? The image will be of the front part of the car and will look like this:

Front of car image

This JavaScript animation will be utilized in an HTML5 banner advertisement so I am hoping to avoid anything that will increase the size of my deliverable substantially. I have been looking online for something similar to this and can't seem to find an example of what I am hoping to accomplish. Any ideas are welcome.

Answer

You don't need javascript, you can just use a CSS3 animation. For example, this would work:

@keyframes drive {
  from {
    transform: scale(0.2);
  }
  to {
    transform: scale(1);
  }
}
.car {
  animation: drive 3s cubic-bezier(0.02, 0.01, 0.21, 1) infinite;
}
<img class="car" src="https://i.stack.imgur.com/oT3DY.png">
</img>

Explanation:

First, we define a drive animation. It starts with a CSS3 transform that scales the image to 1/5th the size, then at the end of the animation, to full size. You can use any css property, even width but transform: scale doesn't force a page render, so your animation is faster.

Then, let's break down the animation property on the .car.

  1. drive - this part is self-explanitory, it tells CSS to use the drive key frames
  2. 3s - makes the animation last 3 seconds
  3. cubic-bezier(0.02, 0.01, 0.21, 1) - sets the curve for the animation to run, so it scales slower the further along it goes.
  4. infinite causes the animation to repeat infinitely.