What is the most efficient way to modify the variables for numerous images within a JavaScript canvas?

I'm a newcomer to using Javascript in a canvas, and coding with javascript overall.

My primary goal is the following:

  • Create numerous fireballs (images) that spawn randomly with each having a fixed y-value and random x-value.
  • The fireballs should then fall at various speeds determined by individual variables.

I have managed to implement the random x positions and locked y values. However, I am struggling with finding a way to assign separate speed variables for each new image to control their falling rate. It would be ideal if this could be applied to every single fireball individually like so:

fireBallSpeed = 10;
fireBallTop = 0;

if (randomSpawn == 1){
    fireBallTop += fireBallSpeed;
    fireBall.style.top = fireBallTop + 'px';
    ctx.drawImage(fireBall, randomX, fireBallTop, 50, 50);
}

Answer №1

To keep track of each fireball, store them in an array and iterate through the array to update their positions.

let fireballs = []
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')

function gameLoop() {
  // Clear the canvas
  ctx.clearRect(0, 0, 800, 300)

  // Update the position of each fireball in the array
  fireballs.forEach(fireball => {
    ctx.fillRect(fireball.x, fireball.y, 10, 10)
    // Update the position for the next frame based on speed
    fireball.y += fireball.speed
  })

  // Request another frame
  requestAnimationFrame(gameLoop)
}

function gameInit() {
  // Create 5 fireballs
  for (let i = 0; i < 5; i++) {
    fireballs.push({ x: Math.random() * 280, y: 5, speed: Math.random() * 2 })
  }
}

// Initialize the game
gameInit()

// Start the game loop
// This function is used for drawing, setInterval should handle logic
// For simplicity, using this function for both
requestAnimationFrame(gameLoop)
<canvas width="800" height="300"></canvas>

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

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

Warning on React component listing due to key issue originating from the parent component

Alert: It is essential that each child in a list has a distinct "key" prop. Please review the render method of ForwardRef(ListItem). A child from RecipientsList was passed. I have located this issue using the react-components debugger tool on Chrome. I ad ...

What is the procedure for updating a state property's value?

Currently, I am in the process of developing a small application that has the ability to fetch data, display it in the DOM, and allow users to select an item to view detailed information about the chosen user. To manage all these functionalities, I am util ...

Retrieve the complete content of a web page, including all HTML and JavaScript elements

After spending several hours researching and experimenting, I find myself a bit confused about the topic at hand. My issue: I am attempting to retrieve the complete HTML content (including dynamically generated JavaScript content) of a specific web page. ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

What is the best way to fetch posts that contain an array of user IDs?

I've been working on implementing a bookmark feature for my website to allow users to save posts, but I'm encountering some issues. The idea is that when a user clicks the bookmark button, their ID should be stored in the saves array. When tryin ...

Importing JSON data into a Backbone.js model

I'm just starting to explore Backbone. Can you help me figure out what I might be missing in this situation? Below is the model I am using: var Item = Backbone.Model.extend({ url: 'json/item.json', parse: function(response){ retu ...

Attempting to use Vue.js for playing MP3 files

Motive: My objective is to incorporate a background sound into my project using a local file that can be played and paused. While loading an external URL file works fine and allows for play/pause functionality, I am encountering issues with the local fil ...

Could you please clarify the specific functionality of this script?

I've been trying to figure out the communication process between (a website that tracks real-time changes in Roblox's catalog and updates the client) and I came across this script while inspecting the site. It seems like this script is responsib ...

The 'export '__platform_browser_private__' could not be located within the '@angular/platform-browser' module

I have encountered an issue while developing an angular application. Upon running ng serve, I am receiving the following error in ERROR in ./node_modules/@angular/http/src/backends/xhr_backend.js 204:40-68: "export 'platform_browser_private' w ...

Guide to dynamically assigning the id attribute of an HTML element using angularjs (1.x)

Given an HTML element that is a div, what is the method to assign a value to its id attribute? The value should be a combination of a scope variable and a string. ...

Having trouble accessing the property 'top' of an undefined object in your Ruby on Rails project?

After thoroughly reviewing all the similar threads on SO regarding this error, none of them provided a solution that worked for me. Here is the flow of events: Go to the new Customer page, fill out the required fields, and click save Invoke a method in ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

Is it possible to trigger a keydown event using a forEach loop?

I've been working on implementing an accessibility feature for a bootstrap accordion. I included the tabindex=0 in each <a> tag in an attempt to make it so that when the user presses the tab key, it opens the corresponding dropdown/accordion. Ho ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...

Trouble getting CSS to load in Webpack

I'm having some trouble setting up Webpack for the first time and I think I might be overlooking something. My goal is to use Webpack's ExtractTextPlugin to generate a CSS file in the "dist" folder, but it seems that Webpack isn't recognizi ...

Incorporating a new dropdown menu above the content of a pre-existing jQuery accordion dropdown, causing the content to shift downwards

Seeking a way to overlay a second-level dropdown menu on top of the content beneath a jQuery accordion-style dropdown. Typically, the jQuery accordion pushes down the content below, but I want the second-level dropdown to remain unaffected. Is there a solu ...

Turn off the incorrect TypeScript error detection

After setting up 'interact.js' using jspm and npm for TypeScript compatibility, I am encountering errors in my code: import { interact } from 'interact.js/interact' // ==> typescript error: TS2307: Cannot find module 'interact. ...

What is the maximum character limit for jQuery?

Here's a code snippet I'm working with: $.get("url") .done(function(data){ alert("success"); alert(JSON.stringify(data)); }) .fail(function(data){ alert("fail"); alert(JSON. ...