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

JSONP Error - "SyntaxError: Unexpected token caught"

Just to start off, I want to mention that I'm new to working with jsonp. This is my first time diving into the world of JSONP. Currently, I'm using a jQuery ajax call to retrieve data from a website. Here's a snippet of my jQuery code: $. ...

Working through JSON arrays in JavaScript

Here is a JSON example: var user = {"id": "1", "name": "Emily"} If I select "Emily," how can I retrieve the value "1"? I attempted the following code snippet: for (key in user) { if (user.hasOwnProperty(key)) { console.log(key + " = " + use ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

onload function prevents further URL redirection

After submitting the form "View this product," a function is triggered to retrieve the product id from the form data. Although I can successfully obtain the form_data, the page does not redirect as expected. I suspect that my function may not have been pr ...

css - flexible div height based on content

Issue encountered: In my website, I have a dynamically generated content inside a specific div. On the left side of the provided URL, you can see the current appearance of the div. It is worth noticing that the height of the container div (mainContent_mid ...

Is there a specific jest matcher available for comparing Array<Objects>?

I'm currently testing the equality of two arrays of objects and have found that the toEqual matcher in Jest only works for arrays of strings. Is there another matcher available in Jest that can handle this condition? Please refrain from marking this a ...

Tips for retaining a number even when the page is refreshed

Is there a way to keep the number increasing even after refreshing the webpage? Currently, the number resets every time the page is refreshed. Any suggestions on how to fix this? Here is the number <form method="POST"> &l ...

a height of 100% with a minimum height of 100%

Is there a way to make the third and fourth rectangles have the same position while filling all the remaining height in %? Keep in mind that we can't change the min-height:100% on the body or html. Feel free to use CSS and HTML for your code solution. ...

What are the steps for me to generate my own unique HTML tag?

Is there a way to create my own custom HTML tags in HTML or HTML5 so that I can develop my unique HTML tag and CSS library like: <mymenu> ul li or some text </mymenu> <heading> Yeah My Own Heading</heading> If yes, please guide m ...

Unable to transform socket.io event into Bacon EventStream

After successfully binding the event on socket.io, the following code was executed: io = require('socket.io')() io.on 'connection', (socket) -> console.log socket.id io.listen 3000 An attempt was made to convert the socket.io ...

Issues with CSS hover event causing animation to fail to trigger

I have a container that contains an image holder and a text holder. I am able to set it so that when hovered over, the image scales and the same effect applies to the text. However, when attempting to set up the image holder hover to scale the image and ...

Encountered an error while building CSS Modules for a Vue.js project

Working on a project in Vue.js, I decided to incorporate CSS modules for my local styles (for sass and scss). However, I continuously encounter a 'Failed to compile error' related to the CSS Loader validation process. Despite attempting various ...

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...

Can you explain the concept of a host server?

Hello, I am new to using cPanel and I recently uploaded a script to my domain directory. While trying to install the script, I was prompted to input my host server information. You can view the screenshot here: https://i.sstatic.net/rrVEX.png ...

Angular.js Issue: Repeating elements must be unique - Index tracking not functioning properly

I have been following a tutorial on the Ionic Framework, which utilizes Angular JS to develop a basic Todo application. The app adds a new task by utilizing the .push() method to append a new task object to an array of task objects. An issue arises when a ...

Leveraging vuejs to dynamically insert a URL within a function

I am attempting to dynamically bind an image path inside a method. It seems feasible, but I'm uncertain if I am implementing the code correctly. Can someone review it? Essentially, I want to retrieve the selected image from the model rather than hardc ...

The code provided creates a web form using HTML and ExpressJS to store submitted information into a MongoDB database. However, there seems to be an issue with the 'post' method, while the 'get' method functions correctly

When I try to submit entries (name, email, address) on localhost:3000 in the browser, the 'post' function is not creating an object in the mongo database even though it works from the postman. The browser displays an error message saying "unable ...

Firefox causing images to have a white border after rendering

My image (.png) has a white border only in Firefox, despite the CSS border property being set to 0. Is there a solution to remove this unwanted border around the image? ...

Library written in JavaScript for extracting CSS that is relevant

Is there a JavaScript tool available that can extract the style information from HTML code? For instance, when given the following HTML snippet, it would output a style block containing all the computed styles applied to each of those elements? Input... ...