首页 > 解决方案 > 如何更新 Javascript 画布中许多不同图像的变量?

问题描述

我是画布中 Javascript 的新手,一般来说是 javascript。

基本上,我想做的是:

我得到了随机的 x 位置和固定的 y 值,但我不知道如何为每个跟踪其速度的新图像设置一个单独的下降变量,例如将其应用于每个单独的火球:

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

标签: javascripthtml5-canvas

解决方案


您应该将每个火球保存到一个数组中并在数组上循环更新每个人的位置。

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>


推荐阅读