Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button.

I have come across libraries that allow me to move images but what I really need is a way to change the images as the rabbit moves within a div on the webpage.

In my 'imgs/' folder, I have the following rabbit images: rabbit-image1.jpg, rabbit-image2.jpg, rabbit-image3.jpg, rabbit-image4.jpg, rabbit-image5.jpg, and rabbit-image6.jpg.

When moving the rabbit from one point to another on the page, I want the images to loop seamlessly until the rabbit reaches its final position, creating the illusion of a running motion.

Any suggestions or tips would be greatly appreciated. Thank you!

Answer №1

To create an animation with images, you simply need to provide the images in order as an array and set a timer.

function ImageAnimation(images, timePerImage) {
    this.images = images;                     
    this.currentTime = 0;                    
    this.currentImage = 0;                   
    this.imageCount = images.length;          
    this.timePerImage = timePerImage || 100;  
};

ImageAnimation.prototype.constructor = ImageAnimation;

ImageAnimation.prototype.tick = function(elapsed) {
    this.currentTime += elapsed;
    if(this.currentTime >= this.timePerImage) {
        this.currentImage++;
        if(this.currentImage >= this.imageCount) {
            this.currentImage = 0;
        }
        this.currentTime = 0;
    }
};

ImageAnimation.prototype.getImage = function() {
    return this.images[this.currentImage];
};

var imageArray = [];
for(var i = 0; i < 6; i++) {
    imageArray[i] = new Image();
    imageArray[i].src = "imgs/image" + (i+1) + ".jpg";
}

var animation = new ImageAnimation(imageArray);

var time = Date.now();
function loop() {
    requestAnimationFrame(loop);
    var elapsed = Date.now() - time;
    time += elapsed;

    animation.tick(elapsed); 
    var image = animation.getImage(); 
    
}

If not using canvas, you can use strings instead of images in the array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The screen is cloaked in a dark veil, rendering it completely inaccessible with no clickable

Utilizing Bootstraps modals, here is my current layout. Within the site's header, there exists a "settings" button that triggers a modal containing various options. These options are not tied to the question at hand. The button responsible for displ ...

Which specific file is being requested when a forward slash (/) is placed immediately after the website URL?

Is it just me being clueless, or is there something unusual about this URL format? I've come across URLs like http://www.example.com/?p=1 quite often and I'm curious to know what exactly is being accessed by it. I usually use URLs such as http:// ...

Align a component vertically in a FlexBox using Material UI

I have a React app where I created a card with specified min width and height, containing only a header. I want to add flexbox that occupies the entire left space with justify-content="center" and align-items="center". This way, when I insert a circular pr ...

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

The XML response from Ajax is returning as empty

My goal is to retrieve XML data from an ajax request and extract information using the DOM. The ajax request itself seems to be working fine as I can access AjaxRequest.responseText without any issues. However, I am encountering an error message stating: ...

Mastering the CSS Art of Working with Sprite Images and Their Positioning

I am currently working on an educational project as a front-end developer, where I aim to clone the Google homepage. To achieve this, I am utilizing Google's own sprite and here is the image of the sprite that I am using. https://i.stack.imgur.com/YT ...

Scroll sideways with AJAX content replacement

I've successfully discovered various methods for loading and replacing content with ajax, as well as ways to hide/show with effects. However, I'm now seeking a technique that allows the new content to slide into a div while the old content slide ...

Activate automatic selection when the input field is disabled

How can I enable auto-select for text in an input field even when it is disabled? Currently, the auto select feature doesn't work when the field is disabled. Here is my HTML: <input type="text" class="form-control" ng-model="gameId" select-on-cli ...

Trouble locating DOM element in Angular's ngAfterViewInit()

Currently, I am attempting to target a specific menu item element within my navigation that has an active class applied to it. This is in order to implement some customized animations. export class NavComponent implements AfterViewInit { @ViewChild(&a ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

How can NodeJS implement ThreadLocal variable functionality without relying on req and res.locals?

In a specific situation, I am required to handle business logic and logging for each request separately. This means that the data stored should not overlap with data from other requests. Using res.locals or req objects is not an option in this case becaus ...

Attempting to use tabs within a tab does not function correctly

Visit the CodePen link here This is the codepen example. <div class="row"> <div class="col s12"> <ul class="tabs2"> <li class="tab col s3"><a href="#test1">Test 1</a></li> <li class=" ...

Learning to monitor for incoming messages in a Discord channel from the ground up

I am eager to understand how to detect new messages exclusively using requests made to the Discord API. While I have mastered loading messages by fetching , I am struggling to grasp how to listen for incoming messages. It appears that this feature is not ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

Having trouble with the filtering feature in Material UI Datagrid

I'm currently using Material UI Data Grid to display a table on my website. The grid has an additional filter for each column, but when I click on the filter, it hides behind my Bootstrap Modal. Is there a way to bring it to the front? https://i.stac ...

A dynamic jQuery plugin that replicates the smooth page sliding animation found in iPhone apps

Currently, I am in search of a jQuery plugin that has the capability to navigate users to different pages on a website with a sleek sliding animation, similar to what we see in some widely used iPhone apps. Despite my best efforts to create this functional ...

"Encountering a hang while using the .save() function and only

Issue with storing data in MongoDB This is only my second attempt at saving data to a database and I am still relatively new to the process. I have a form on my HTML page that sends string data to be saved in a MongoDB database. I successfully connected t ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Having issues with npm python-shell integration within electron framework

I'm currently attempting to establish a connection between a python script and an Electron app by utilizing the npm's python-shell package. The requirement is for the script to be executed whenever a button is clicked. So, let's assume my d ...

Is it better to have Angular and Laravel as separate applications or should Laravel serve the Angular app?

I have a new project in the works, aiming to create a large SAAS application. Although I come from a CakePHP background, I've decided to use Laravel and Angular for this venture. As I navigate through unfamiliar territory with these technologies, I a ...