Balls
by phejny
HTML
<canvas id="scene" width="500" height="500">
</canvas>
CSS
#scene {
border: 1px solid #000000;
}
JavaScript
class Ball {
constructor(x, y, size, color) {
this.size = size;
this.position = {
x: x,
y: y
};
this.move = {
x: 0,
y: 0
};
this.color = color;
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.size / 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
update(ms) {
this.position.x += this.move.x * ms / 1000;
this.position.y += this.move.y * ms / 1000;
}
}
class Scene {
constructor(ctx) {
this.ctx = ctx;
this.objects = [];
}
addObject(object) {
this.objects.push(object);
}
update(ms) {
this.objects.forEach(function(object) {
object.move.y *= Math.pow(0.9, ms / 1000); //Friction
object.move.x *= Math.pow(0.9, ms / 1000); //Friction
object.move.y += 10; //Gravity
object.update(ms);
//Bottom border
if (object.position.y >= ctx.canvas.height - object.size / 2) {
object.position.y = ctx.canvas.height - object.size / 2;
object.move.y = -object.move.y * 0.9; //Bounce
} else
//Top border
if (object.position.y <= 0 + object.size / 2) {
object.position.y = 0 + object.size / 2;
object.move.y = -object.move.y * 0.9; //Bounce
}
//Right border
if (object.position.x >= ctx.canvas.height - object.size / 2) {
object.position.x = ctx.canvas.width - object.size / 2;
object.move.x = -object.move.x * 0.9; //Bounce
} else
//Left border
if (object.position.x <= 0 + object.size / 2) {
object.position.x = 0 + object.size / 2;
object.move.x = -object.move.x * 0.9; //Bounce
}
});
}
draw() {
//ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
this.objects.forEach(function(object) {
object.draw(ctx);
});
}
}
var canvas = document.getElementById("scene");
var ctx = canvas.getContext("2d");
var scene = new...