Developing HTML5 animation by utilizing sprite sheets

Struggling to create an engaging canvas animation with the image provided in the link below.

Please take a look at https://i.stack.imgur.com/Pv2sI.jpg

I'm attempting to run this sprite sheet image for a normal animation, but unfortunately, I seem to be encountering some issues.

Here is the code snippet I have been working on:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>

 <canvas id='canvas'></canvas><br />
 <button onclick='moveLeft()'>Left</button>
 <button onclick='moveRight()'>Right</button>
 <script>
 var canvasWidth = 650; 
 var canvasHeight = 350;
 
 var spriteWidth = 379; 
 var spriteHeight = 133; 
 
 var rows = 2; 
 var cols = 8; 
 
 var trackRight = 0; 
 var trackLeft = 1; 
 
 var width = spriteWidth/cols; 
 var height = spriteHeight/rows; 
 
 var curFrame = 0; 
 var frameCount = 8; 
 
 var x=0;
 var y=200; 
 
 var srcX; 
 var srcY; 
 
 var left = false; 
 var right = true;
 
 var speed = 12; 
 
 var canvas = document.getElementById('canvas');
 canvas.width = canvasWidth;
 canvas.height = canvasHeight; 
 
 var ctx = canvas.getContext("2d");
 
 var character = new Image(); 
 character.src = "jpg.jpg";
 
 function updateFrame(){
 curFrame = ++curFrame % frameCount; 
 srcX = curFrame * width; 
 ctx.clearRect(x,y,width,height); 
 
 if(left && x>0){
 srcY = trackLeft * height; 
 x-=speed; 
 }
 if(right && x<canvasWidth-width){
 srcY = trackRight * height; 
 x+=speed; 
 }
 }
 
 function draw(){
 updateFrame();
 ctx.drawImage(character,srcX,srcY,width,height,x,y,width,height);
 }
 
 
 function moveLeft(){
 left = true; 
 right = false; 
 }
 
 function moveRight(){
 left = false;
 right = true; 
 }
 
 setInterval(draw,100);
 
 </script>
</body>
</html>

The current behavior of the animation is not as expected, only showing the center area of the image. Any suggestions on how to resolve this issue?

Answer №1

Your spritesheet needs to have consistent widths for each step to avoid animation shifts. It is possible to animate a spritesheet using only CSS. Here is an example with this spritesheet:

<body>
    <style>
        #animSheet {
            background-image: url("spritesheet.png");
            width: 256px;
            height: 256px;
            animation: animSheet 1s steps(6) infinite;
        }

        @keyframes animSheet {
            0% {
                background-position: 1536px;
            }

            100% {
                background-position: 0px;
            }
        }
    </style>

<div id="animSheet"></div>

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

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

Expanding Module Scope to Just the Request (employing Require, Node.js)

Original Query The project I am currently working on is using Express to manage HTTP requests. The structure of the project is quite intricate, with multiple embedded require statements. Our main challenge lies in maintaining access to the request and re ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Is it possible to remove a specific directory from the webpack build configuration in a vue-cli-3 setup?

After spending 3 hours adding the line: exclude: ['./src/assets/sass'] in 20 different places, I am seeking guidance on where it should actually be placed. Below is my current setup for the css-loader (util.js): 'use strict' const path ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

In making reference to a particular subpage within a parent page

My website is designed with all inner pages linked to one master file. I'm looking to change the title font size on just one specific page, without affecting the rest of the pages that use the master file. Is there a way to target a specific page titl ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

How can NodeJS functions leverage parameters such as req, res, and result?

As a newcomer to JS, particularly Node and Express, I am in the process of learning how to build an API through tutorials. Along the way, I am also exploring various special features of JS such as let/const/var and arrow functions. One common pattern I no ...

Tips for enhancing the color saturations of cells that overlap in an HTML table

My goal is to enhance the color of overlapping cells in my HTML tables. For instance, when I click on cell 2, the .nextAll(':lt(5)') method will change the class of the next 4 cells. https://i.stack.imgur.com/mwv8x.png Next, clicking on cell 3 ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

Best practices for resolving classlist.toggle issues with my dark mode button

The code seems to work only the first time, but after activating light mode again, the sun stops appearing. How can I ensure that the 'bi-sun' class is added back every other click or when dark mode is not activated? function theme() { do ...

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

What are the best scenarios for implementing jQuery-ui plugin as opposed to Backbone View?

I am feeling uncertain about the concept of "componentization" in web UI development. When I need a component, should I develop my own jQuery-UI plugin or opt for creating a MarionetteComponent if I am using Backbone.Marionette? Both options provide reusa ...

"Encountering a challenge when trying to fetch the value of an undefined or null

When it comes to validating the delivery date entered, I have implemented the following code to ensure it is not earlier than the current date... I have utilized custom validation using jQuery... Here is my model: [UIHint("Date")] [DeliveryDateC ...

Using jQuery to define active or hover background images

I'm currently working on a list containing 5 items, with the first one active by default (thanks to jQuery adding a 'active' class). Each item has its own background image. When I click on any of the list items, another div gets updated with ...

Is there a way to extract the text that is displayed when I hover over a specific element?

When I hover over a product on the e-commerce webpage (), the color name is displayed. I was able to determine the new line in the HTML code that appears when hovering, but I'm unsure how to extract the text ('NAVY'). <div class="ui ...

Rails offers a unique hybrid approach that falls between Ember and traditional JavaScript responses

My current project is a standard rails application that has primarily utilized HTML without any AJAX. However, I am planning to gradually incorporate "remote" links and support for JS responses to improve the user experience. While I acknowledge that gener ...

Mysterious occurrences always seem to unfold whenever I implement passport for user authentication in my Node.js and Express applications

At first, I wrote the following code snippet to define LocalStrategy: passport.use( 'local-login', new LocalStrategy({ usernameField:'username', passwordField: 'password', passReqtoCallback: tr ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...