JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="ball-canvas" width="900" height="600"></canvas>
JavaScript
var canvas = document.getElementById('ball-canvas');
var context = canvas.getContext('2d')
var radius = 50;
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',
}
var redCircle ={
x:450,
y:h / 2,
radius:radius,
color:'red',
}
var blueCircle ={
x:850,
y:h / 2,
radius:radius,
color:'blue',
}
// 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();
}
}
// Random float between
function randomFloatBetween(minValue,maxValue,precision){
if(typeof(precision) == 'undefined'){
precision = 2;
}
return parseFloat(Math.min(minValue + (Math.random() * (maxValue - minValue)),maxValue).toFixed(precision));
}
function animate(){
// Yellow Circle
circles[0].x=randomFloatBetween(1,900);
circles[0].y=randomFloatBetween(1,600);
// Blue Cirlce
circles[1].x+=-1;
...