JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="balling" width="700" height="600"></canvas>
CSS
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#balling {
border:1px solid rgb(0, 0, 0);
}
JavaScript
var canvas = document.getElementById('balling');
var context = canvas.getContext('2d');
var ballBasket = [];
var ballFactory = function (new_x, new_y) {
var b = {};
b.posBall = {
x: new_x,
y: new_y
};
b.radius = 40;
b.startAngle = 0;
b.endAngle = Math.PI * 2;
b.anticlockwise = false;
b.radians = 0;
b.xMove = Math.random();
b.yMove = Math.random();
b.speed = 10;
b.angle = 80;
b.velocityX = 5;
b.velocityY = 5;
// get a random color
b.color = '#' + Math.random().toString(16).substr(-6);
return b;
}
ballBasket.push(ballFactory(160, 180));
//Math to make the ball move
function moveBall(CurrentBall) {
CurrentBall.radians = CurrentBall.angle * Math.PI / 180;
CurrentBall.xMove = Math.cos(CurrentBall.radians) * CurrentBall.speed * CurrentBall.velocityX;
CurrentBall.yMove = Math.sin(CurrentBall.radians) * CurrentBall.speed * CurrentBall.velocityY;
}
//Function to draw the ball
function DrawReset() {
//Reset Canvas
context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
//Drawing all of the balls
for (var i = 0; i < ballBasket.length; i++) {
var currentBall = ballBasket[i];
context.fillStyle = currentBall.color;
context.beginPath();
context.arc(currentBall.posBall.x, currentBall.posBall.y, currentBall.radius, 0, 2 * Math.PI, false);
context.closePath();
context.fill();
}
}
// Animate and call the function to move the ball
setInterval(Move, 20);
//The function to make it move, reset canvas for movement and color/create shape of ball
function Move() {
DrawReset();
for (var i = 0; i < ballBasket.length; i++) {
var currentBall = ballBasket[i];
//Power to make it move
currentBall.posBall.x += currentBall.xMove;
currentBall.posBall.y += currentBall.yMove;
//checks for ball hitting the Wall
if (currentBall.posBall.x >...