JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="ball-canvas" width="300" height="200"></canvas>
CSS
canvas {
box-shadow: 0 0 3px #aaa
}
JavaScript
var canvas = document.getElementById('ball-canvas');
var context = canvas.getContext('2d')
var radius = 20;
var strokewidth = 2;
var strokestyle = '#666';
var frameCount=0;
var w = canvas.width;
var h = canvas.height;
// Circle Objects
var yellowCircle ={
x:50,
y:h / 2,
radius:radius,
color:'yellow',
moveX: 1,
moveY: -1
}
var redCircle ={
x:100,
y:h / 2,
radius:radius,
color:'red',
moveX: -2,
moveY: -1
}
var blueCircle ={
x:150,
y:h / 2,
radius:radius,
color:'blue',
moveX: 2,
moveY: 3
}
// Create empty array and then push cirlce objects into array
var circles=[];
circles.push(yellowCircle, blueCircle, redCircle);
// Clear last circle and draw again
function draw() {
context.clearRect(0,0,canvas.width, canvas.height); // Clear the circle from the from page
for(var i=0;i<circles.length;i++){
var c=circles[i];
context.beginPath();
context.fillStyle=c.color // Set the color of the circle using key:valuecontext.fill();
context.lineWidth=strokewidth;
context.strokeStyle=strokestyle;
context.stroke();
context.arc(c.x,c.y,c.radius,0,Math.PI*2); // X-axis Position, y-axis Position, radius, % of fill, ?
context.closePath();
context.fill();
}
}
function animate(){
for(var i=0;i<circles.length;i++){
var c = circles[i];
// check rebounds
if (c.x - c.radius <= 0 || c.x + c.radius >= canvas.width)
c.moveX = -c.moveX;
if (c.y - c.radius <= 0 || c.y + c.radius >= canvas.height)
c.moveY = -c.moveY;
// Yellow Circle
c.x...