简体   繁体   中英

How can I update variables for many different images in a Javascript canvas?

I am new to Javascript in a canvas, and javascript in general.

Basically, what I am trying to do is:

  • have many different randomly spawning fire balls (images), that all start at a fixed y value and a random x value.
  • They should then fall at a speed of a variable.

I got the random x position, and the fixed y value, but I don't know how I can have a separate falling variable for each new image that tracks it's speed, such as applying this to each individual fire ball:

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

You should save each fireball into an array and loop over the array updating each one's position.

 let fireballs = [] const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') function gameLoop() { // Clear the canvas ctx.clearRect(0, 0, 800, 300) // Loop over each fireball and update their positon fireballs.forEach(fireball => { ctx.fillRect(fireball.x, fireball.y, 10, 10) // Set the new position for the next frame using the 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 }) } } // Init the game gameInit() // Start the game loop // This function should only be used for the drawing portion // and setInterval should be used for the logic // For simplicity I am going to use this for both requestAnimationFrame(gameLoop) 
 <canvas width="800" height="300"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM