JSFiddle - React, Tailwind, and code Playground
by Adolfo
HTML
<canvas id="myCanvas" width="480" height="320"></canvas>
CSS
canvas { background: #eee; }
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 10;
var x = canvas.width/2;
var y = canvas.height-ballRadius;
var dx = 2;
var dy = -2;
var c = false; //cambia color
var r; //rojo
var g; //verde
var b; //azul
function drawBall() {
r = Math.floor(Math.random() * 256);
g = Math.floor(Math.random() * 256);
b = Math.floor(Math.random() * 256);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
if (c){
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
c=false;
}
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
c = true;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
c = true;
}
x += dx;
y += dy;
}
setInterval(draw, 5);