Choose the appropriate sprite based on the calculated result

I have a PNG file with 30 sprites in it. After converting it into CSS using , I am facing an issue with my JavaScript code. The script generates a random number between 1 and 30, and I need to select the corresponding sprite based on this number.

.spriteBigPart {
    display: inline-block;
    background: url('../img/parts.png') no-repeat;
}
.part_1  {
    background: url('../img/parts.png') no-repeat -26px -20px;
    width: 121px;
    height: 121px;
}
...
.part_30 {
    background: url('../img/parts.png') no-repeat -4637px -20px;
    width: 121px;
    height: 121px;
}
<div class="row">
  <span class="spriteBigPart **random_number_between_1_and_30**"></span>
</div>

Answer №1

In my approach, I would execute the following code:

var span = document.querySelector(".spriteBigPart");
span.setAttribute("class", "spriteBigPart part_" + random);

I found Sprite Cow to be extremely helpful in crafting the code above. However, it's worth noting that while it's a great tool, the generated code might not always be suitable for every scenario. You may need to make adjustments based on your specific implementation choices :-)

var fps = 4;
var head = 0;
var fpsEl = document.getElementById("fps");
var debugEl = document.getElementById("debug");
var marioEl = document.getElementById("mario");

var anims = {
  hammerWL: [0, 2, 1, 3], // walk left
  hammerWR: [7, 5, 6, 4]  // walk right
};

var anim = [].concat(
  anims.hammerWL, // L
  anims.hammerWL, // L
  anims.hammerWR, // R
  anims.hammerWL, // L
  anims.hammerWR  // R
);

fpsEl.value = fps;
fpsEl.onclick = updateFps;
fpsEl.onkeyup = updateFps;
fpsEl.onchange = updateFps;
debug.onclick = toggleDebug;
debug.onchange = toggleDebug;

function updateFps () {
  fps = parseInt(this.value, 10) || 0;
}

function updateFrame (frame) {
  marioEl.setAttribute("class", frame);
}

function toggleDebug () {
  var c = this.checked ? "debug" : "";
  document.body.setAttribute("class", c);
}

// !function loop () { ... }();
// is a shortcut for
// loop(); function loop () { ... }
// declared and called at the same time

!function loop () {
  if (fps === 0) {
    setTimeout(loop, fps);
  } else {
    // head = 0, 1, 2, ..., 0, ...
    head = (head + 1) % anim.length;
    updateFrame("frame_" + anim[head]);
    setTimeout(loop, 1000 / fps);
  }
}();
html {
  height: 100%;
}
body {
  margin: 0;
  height: 100%;
  background: black;
}
#controls {
  background: #ddd;
  line-height: 40px;
  padding: 0 .5em;
  height: 40px;
}
#fps {
  width: 50px;
}
#stage {
  position: relative;
  background: yellow;
  border: 10px solid black;
  height: calc(100% - 60px);
  width: calc(100% - 20px);
}

/* sprite */

#mario {
  position: absolute;
  left: 50%;
  bottom: 0;
  height: 0;
  width: 0;
}
#mario img {
  display: block;
  position: absolute; 
  background: url(https://i.sstatic.net/yScim.png);
}
.debug #mario img {
  background-color: #0090ff;
}

/* frames / hammer walk left */

#mario.frame_0 img {
  background-position: -4px -10px;
  width: 26px; height: 58px;
  left: -13px; bottom: 0;
}
#mario.frame_1 img {
  background-position: -70px -24px;
  width: 52px;  height: 32px;
  left: -37px; bottom: 0;
}
#mario.frame_2 img {
  background-position: -162px -10px;
  width: 30px; height: 58px;
  left: -15px; bottom: 0;
}
#mario.frame_3 img {
  background-position: -232px -24px;
  width: 50px; height: 32px;
  left: -37px; bottom: 0;
}

/* frames / hammer walk right */

#mario.frame_4 img {
  background-position: -310px -24px;
  width: 50px; height: 32px;
  right: -37px; bottom: 0;
}
#mario.frame_5 img {
  background-position: -400px -10px;
  width: 30px; height: 58px;
  right: -15px; bottom: 0;
}
#mario.frame_6 img {
  background-position: -470px -24px;
  width: 52px; height: 32px;
  right: -37px; bottom: 0;
}
#mario.frame_7 img {
  background-position: -562px -10px;
  width: 26px; height: 58px;
  right: -13px; bottom: 0;
}
<div id="controls">
  <label>FPS <input id="fps" type="number" min="0" max="12"></label>
  <label>Debug <input id="debug" type="checkbox"></label>
</div>
<div id="stage">
  <div id="mario">
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
  </div>
</div>

https://i.sstatic.net/yScim.png

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

Trouble with mobile compatibility for .json file content population in HTML elements script

Check out THIS amazing page where I have a series of placeholders for phone numbers in the format: 07xxxxxxxx. By simply clicking the green button "VEZI TELEFON", each placeholder in the green boxes gets replaced with a real phone number from a JSON file u ...

Manipulating the size of one div automatically adjusts the size of the other, as they are

I have encountered an issue while trying to manage two resizable divs. I am looking for a solution where changing the size of one div will automatically adjust the size of the other div along the grid, and vice versa. Currently, I am only able to achieve ...

JavaScript Dynamic Array for Generating GoogleChart JSON Data

I am attempting to create a line chart using Google Charts ( ), but I am struggling with formatting the array for the chart. The required array format is as follows : var data = google.visualization.arrayToDataTable([ ['Year', 'Sales&ap ...

Dynamic path variables showcased in a static JSON configuration file

There is a JSON configuration for a backend CLI utility: { "searchRoots": ["$HOME"], "list": [] } If this was done with JavaScript, it would be: module.exports = { searchRoots": [process.env.HOME], list: [] }; The issue with using JSON instea ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...

Arranging information within the Ngb-Accordion

Welcome to the code snippet showcasing how to create an accordion in Angular: <ngb-accordion [closeOthers]="false" activeIds="0"> <ng-container class="card" *ngFor="let post of Posts"> <ngb-panel title="{{post.title}} - ...

The absence of ellipses in Typography MUI is a glaring omission

I'm looking to truncate long text with an ellipsis, but it doesn't seem to be working. Is there something wrong with my code or how can we improve it? CODESANDBOX -----> CLICK HERE <Typography variant="body2" color="blac ...

Javascript: A Fun Game of Questions and Answers

When using JavaScript exclusively, I have an array consisting of four questions, four correct answers, and four incorrect answers. The use of arrays is essential to maintain order in the data. As each question is displayed, a random number is generated by ...

Challenges with Scope in Using AJAX Calls within an Infowindow

Could it be a scope issue? Feel free to correct me if I'm mistaken. I've got a for loop that's placing markers on my map. Each marker has a different infowindow that loads content using ajax callbacks. This is a simplified version of the s ...

Is it possible to arrange two items in one column and the rest as columns in MaterialUI Grid?

I need help arranging my arrows in a MaterialUI grid where one points up and the other points down. How can I achieve this layout? Attached below is an image of my current setup and the desired outcome. Here is my code: <Paper className={classes.paper ...

Header of table remains fixed as user scrolls through data, allowing for easy reference. The left

Above, I have utilized some code from another answer here to display a table. However, I am now contemplating the possibility of customizing it so that the first column remains fixed for horizontal scrolling. Currently, I'm employing the following as ...

What is the best way to store a file object in React's state?

I am currently working on setting the state for a file object that is being passed between modals before it is uploaded to the server. Below is the code snippet that demonstrates what I am attempting to achieve. const initialState = { selectedD ...

The communication between AWS Lambda and an SQS queue is currently experiencing a disruption in message delivery

I am facing an issue with sending a hardcoded message to SQS from Lambda. While running the lambda function locally, I am able to see messages in SQS. However, when deployed as an image, the lambda function is not working properly. I have already added Ama ...

How can I transform a multidimensional array in PHP into a nested list in HTML?

I am working with an array that is nested and can be "endless" due to the complexity of family trees. Here is a simplified example: Array ( [id] => 121 [name] => Very Important Dogs Bowey Showey [gen] => 0 [mother] => Array ...

Learn how to make a specific row blink twice with the power of Vue.js and Vuetify

Once a record is successfully created, I have implemented a feature where an alert message appears in green if the API returns 200 OK, and red if not. This functionality is currently working flawlessly thanks to my use of Vuex + Vuetify Snackbar. this.noti ...

Receiving POST data in the req.body object with only the key specified in Express.js

I am encountering an issue with my current POST request. There is a simple function in place that handles the sending of data to the server using AJAX. handleSubmit(event) { var http = new XMLHttpRequest(); // object allows for making http requests // ...

Modifying the clone() property in three.js affects all the meshes in my project

I am looking to create 100 identical cubes with a gradual decrease in opacity for each cube. This is my current loop implementation: var geometry = new THREE.BoxGeometry(0.15,0.15,0.15); var material = new THREE.MeshNormalMaterial(); var cube = new THREE. ...

What causes axios to return a z_buf_error?

I've encountered an issue with axios returning an error cause: Error: unexpected end of file at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) { errno: -5, code: 'Z_BUF_ERROR' I'm puzzled as to why this functio ...

Create an ASP button with drag and drop functionality

Is there a way to enable drag and drop functionality for an asp:Button element? Also, how can I retrieve the coordinates of the button after implementing jquery drag and drop? My goal is to store these coordinates in a database so that when I revisit the ...

What is the process for capturing input values when the enter key is pressed?

Is there a way to submit a form on Enter key press without refreshing the page? Below is my code snippet: PHP code: <form action="profile/update_profile" method="post" id="business_name_data"> <input type="hidden" name="business_name" id="busi ...