如何更新Javascript画布中许多不同图像的变量?

时间:2018-07-03 22:21:00

标签: javascript html5-canvas

对于画布中的Javascript和javascript,我是新手。

基本上,我想做的是:

  • 有许多不同的随机生成的火球(图像),它们都以固定的y值和随机的x值开始。
  • 然后它们应该以可变速度下降。

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

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

1 个答案:

答案 0 :(得分:0)

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

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>