How to make a moving picture JavaScript

This article will show you how to create a moving image using JavaScript, with a step-by-step example.

Creating a Moving Picture with JavaScript

Animations on webpages are an excellent way to add visual interest and engage the user. Creating a moving picture is one of the most basic and effective animations that can be created using JavaScript. To illustrate how to create a moving picture with JavaScript, this example creates a simple animation of a car driving across the screen.

The HTML code for the animation will include a <div> element to contain the picture and a <script> element to contain the JavaScript code.


<div id="carContainer">
    <img src="car.png" id="car">
</div>
<script src="animation.js"></script>

The <div> element contains the image of the car. The <script> element loads the JavaScript code that will animate the car. The JavaScript code for the animation is as follows:


// Get the car element
let car = document.getElementById('car');

// Set the initial position of the car
let carX = 0;

// Set the speed of the car
let carSpeed = 5;

// This function will be called 20 times per second
function animate() {
    // Increase the car’s position
    carX += carSpeed;

    // Move the car
    car.style.transform = 'translateX(' + carX + 'px)';

    // If the car has moved off the screen, reset it
    if (carX > window.innerWidth) {
        carX = -200;
    }
}

// Call the animate function every 20 milliseconds
setInterval(animate, 20);

The animate() function is called every 20 milliseconds. This function increases the position of the car and moves it across the screen. If the car moves off the screen, it is reset to the left side of the screen. The animation can be changed by adjusting the speed of the car and the interval at which the animate() function is called.

By combining HTML and JavaScript, a simple animation of a car driving across the screen can be created. Animations are an excellent way to add visual interest and engage the user, and this example demonstrates how to create a moving picture with JavaScript.

Answers (0)