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

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...

Arranging divs in a row using jQuery sortable technique

Greetings! I have been attempting to achieve horizontal sorting for two divs but have encountered a couple of issues. Firstly, the divs do not align correctly upon initial page load and secondly, while they can be dragged around, the sortable functionality ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

Information has been extracted from the source, however, no content is being shown

Recently, I developed a web application with an AngularJS frontend and Rails backend. I uploaded my frontend code to JSFIDDLE. Meanwhile, the rails backend on the index page is returning some JSON: [{"id":1,"name":null,"user_id":null,"created_at":"2013-1 ...

Activate event starting from parent and ascending through child nodes

When I have a table inside a <div class="timely"></div>, and within that table is a <th class="prev"><i>previous</i></th>, Chrome developer tools show an event listener on the <th>. However, Firefox developer tools ...

When the mouse hovers over the text inside a div, the link does not work in Internet Explorer

Here is some code for demonstration. I'm facing an issue where the link spans over the entire div, which works perfectly in Firefox. However, in IE, when I hover over the text, the cursor changes to a text cursor and the link doesn't work there. ...

Saving real-time information to MongoDB with Node.js

What is the best way to use JSON.stringify and send it to my mongoDB Database? For instance: import express from 'express'; let data_record = JSON.stringify({**any content**}) This snippet of code will automatically fetch data every 60 second ...

Sending back an HTTP response code from PHP to AJAX

I'm currently working on creating a login page for a website. The functionality involves using AJAX to send a request to a PHP script that verifies the username and password input. If the query returns a successful result, I use http_response_code(200 ...

Trouble getting a sticky element to align with a two-column grid within a parent container

I'm looking to keep one column sticky in a two-column grid setup. My goal is to create a vertical navigation bar that's specific to a particular div within a single-page site, with a fixed horizontal navbar across the entire page. However, I&apos ...

The AudioPlayer refuses to play following a track change

I am looking to implement an audio player in React Nextjs that features interactive dots, each representing an audio track. The functionality I want is such that clicking on a dot will pause the currently playing track (if any) and start playing the select ...

Struggling to retrieve data from a MongoDB database in JSON format via an API call? If you're working with JavaScript, Node.js, Express, and MongoDB, we can help you

Below is how I establish the connection to the database: > // Connecting MongoDB using MongoClient > > const MongoClient = require('mongodb').MongoClient > > const url = 'url is used' > > const dbName = 'vir ...

Arranging the Bars in a Bar Chart Using Chart.JS

Lately, I've been playing around with ChartJS and encountering an issue with sorting the bars in descending order, from lowest to highest. Despite my efforts to troubleshoot, I haven't had any success in resolving it. ...

Bottom of the page: Bootstrap dilemma

After designing two footers, I decided to use CSS with the code position: absolute for the second footer. However, this change caused issues with the functionality of the first footer. The display now appears as follows: ...

There appears to be an issue with the server, as it is reporting a TypeError with the _nextProps.children property not

As a newcomer to coding, this is my first question on the forum. I appreciate your understanding and patience as I navigate through some challenges. I'm currently working on making my NextJS SSR app responsive, but after modifying the index.js and ot ...

Transferring data from JavaScript variables to PHP function through AJAX requests

Within my dashboard.php, there is a JavaScript function triggered by a button click event named getTeamMembers. This function receives values from the user's interaction and passes them to a PHP function also present in dashboard.php. Despite my effo ...

Choosing nested elements using CSS

Looking to target a specific element within a shared class, I'm struggling to find the right method to pinpoint the exact entry of this element. What I need to do is hide the current photo (pic2.jpg) and replace it with another image (pic3.jpg) in the ...

"Is there a way to align a span element on the same line as an h

I'm attempting to align a text-number (span) next to an entry-title (h2) on the same line, with the entry-meta block on the following line, including having the reading time float left. I could use some help with my CSS implementation. Thank you. Ex ...

Encountering a NextJS error with head component

Trying to incorporate the head element into a NextJS page format has proven challenging. Despite consulting the official documentation, implementing next/head to add <head> has resulted in an error within the code block. Code: import Head from &apos ...

The gap separating the three columns in the DIVs structure

Here is an example that I need The images are being loaded from a MySQL while loop, and I want the spacing between them to be such that the left column and right column touch each side with the middle image centered. Just like in the picture :D This is m ...

Customize the CSS styling of third-party components in different pages using NextJS

When working with third-party components, you can include their styles by importing their stylesheet into your component or _app.tsx file. For detailed instructions on how to do this, you can refer to Next.js documentation. Another option is to add the sty ...