javascript - 如何更新 Javascript 画布中许多不同图像的变量?
问题描述
我是画布中 Javascript 的新手,一般来说是 javascript。
基本上,我想做的是:
- 有许多不同的随机生成的火球(图像),它们都以固定的 y 值和随机的 x 值开始。
- 然后它们应该以可变的速度下降。
我得到了随机的 x 位置和固定的 y 值,但我不知道如何为每个跟踪其速度的新图像设置一个单独的下降变量,例如将其应用于每个单独的火球:
fireBallSpeed = 10;
fireBallTop = 0;
if (randomSpawn == 1){
fireBallTop += fireBallSpeed;
fireBall.style.top = fireBallTop + 'px';
ctx.drawImage(fireBall, randomX, fireBallTop, 50, 50);
}
解决方案
您应该将每个火球保存到一个数组中并在数组上循环更新每个人的位置。
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>
推荐阅读
- spring-mvc - 基于不同 Spring Securirty 角色的不同 Thymeleaf 布局装饰器
- javascript - 手风琴无法正确滚动到展开的元素
- html - 通过 ajax 或函数调用在 HTML Dropdown 中的动态值
- vb.net - 如何从 vb.net 中的 IP 地址中减去数字
- c# - 登录后不包括 IdentityServer AdditionalClaims
- jquery - 无法读取未定义错误的属性“附加”是什么意思?
- parameters - 读取 Revit 族文档的所有参数
- python - Tensorflow 1.x 错误:提要的值不能是 tf.Tensor 对象。恢复占位符
- ios - Firebase 推送通知不适用于单个设备 ios,但适用于用户段
- c - Visual Studio Building static lib 获取未解析的外部符号