Javascript 如何在MDN教程中减缓反弹球
下面我将尝试使用ES6类声明完成本教程 我的程序中的弹跳球的移动速度比教程中的大纲要快得多。我已经设置了新创建的球实例的速度;但是,球实例仍然移动得太快Javascript 如何在MDN教程中减缓反弹球,javascript,canvas,Javascript,Canvas,下面我将尝试使用ES6类声明完成本教程 我的程序中的弹跳球的移动速度比教程中的大纲要快得多。我已经设置了新创建的球实例的速度;但是,球实例仍然移动得太快 // setup canvas var canvas = document.querySelector('canvas'); var ctx = canvas.getContext('2d'); var width = canvas.width = window.innerWidth; var height = canvas.height
// setup canvas
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
// function to generate random number
function random(min, max) {
let num = Math.floor(Math.random()*(max-min)) + min;
return num;
}
class Ball {
constructor(x, y, velX, velY, color, size) {
this.x = x;
this.y = y;
this.velX = velX;
this.velY = velY;
this.color = color;
this.size = size;
}
draw() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
}
update() {
if ((this.x + this.size) >= width) {
this.velX = -(this.velX);
}
if ((this.x - this.size) <= 0) {
this.velX = -(this.velX);
}
if ((this.y + this.size) >= height) {
this.velY = -(this.velY);
}
if ((this.y - this.size) <= 0) {
this.velY = -(this.velY);
}
this.x += this.velX;
this.y += this.velY;
};
}
function loop() {
let balls = [];
ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
ctx.fillRect(0, 0, width, height);
while (balls.length < 25) {
let size = random(10,20);
let ball = new Ball(
// ball position always drawn at least one ball width
// away from the edge of the canvas, to avoid drawing errors
random(0 + size,width - size),
random(0 + size,height - size),
5,
5,
'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')',
size
);
balls.push(ball);
}
for (let i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].update();
}
requestAnimationFrame(loop);
}
loop();
错误是将let balls=[]放入循环函数中
只要把它移到外面,一切就会开始工作
var canvas=document.querySelector'canvas';
var ctx=canvas.getContext'2d';
var width=canvas.width=window.innerWidth;
var height=canvas.height=window.innerHeight;
//函数生成随机数
函数最小值,最大值{
设num=Math.floorMath.random*max-min+1+min;
返回num;
}
班级舞会{
构造器X、y、velX、velY、颜色、尺寸{
这个.x=x;
这个。y=y;
this.velX=velX;
这是一个很好的例子;
这个颜色=颜色;
这个。大小=大小;
}
画{
ctx.beginPath;
ctx.fillStyle=this.color;
ctx.arcthis.x,this.y,this.size,0,2*Math.PI;
ctx.fill;
}
更新{
如果this.x+this.size>=宽度{
this.velX=-this.velX;
}
如果this.x-this.size=高度{
this.velY=-this.velY;
}
如果这个.y-这个.size