JSFiddle - React, Tailwind, and code Playground
by sinechris
HTML
<canvas id="myCanvas" width="500" height="400"></canvas>
JavaScript
$(document).keydown(function(event){
var key = event.which;
switch(key)
{
case 38:
console.log('up');
iterateBalls(function(ball){
ball.vy += 20;
});
break;
case 37:
console.log('left');
iterateBalls(function(ball){
ball.vx -= 20;
});
break;
case 39:
console.log('right');
iterateBalls(function(ball){
ball.vx += 20;
});
break;
case 40:
console.log('down');
iterateBalls(function(ball){
ball.vy -= 20;
});
break;
default:
console.log('Any other key was pressed: ', key);
}
});
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
// haha iterateballs
function iterateBalls(callback){
for (var i = balls.length - 1; i >= 0; i--) {
callback(balls[i]);
};
}
// Define ball object
function Ball(x,y,r,vx,vy,elasticity, fillStyle){
this.x = x,
this.y = y,
this.r = r,
this.vx = vx,
this.vy = vy,
this.elasticity = elasticity,
this.fillStyle = fillStyle;
};
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function detectWallCollision(ball){
// Detect Right Edge Collision
if (ball.x + ball.r >= canvas.width){
if (ball.vx > 0){
ball.vx *= -1;
}
ball.vx *= ball.elasticity;
}
// Detect Left Edge Collision
if (ball.x - ball.r <= 0) {
if (ball.vx < 0){
ball.vx *= -1;
}
ball.vx *= ball.elasticity;
}
// Detect Bottom Edge Collision
if (ball.y + ball.r >= canvas.height){
if (ball.vy > 0) {
ball.vy *= -1;
}
ball.vy *= ball.elasticity;
}
// Detect Top Edge Collision
if(ball.y - ball.r <= 0){
if (ball.vy < 0) {
ball.vy *= -1;
}
ball.vy *= ball.elasticity;
}
}
// Make some random balls
var balls = [];
for (i=0; i<100; i++) {
var elasticity = 0.75,
vx = getRandomInt(-15, 15),
vy = getRandomInt(-15,...