JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas"></canvas>
CSS
canvas {
width: 300px;
height: 200px;
border: 1px solid #000;
}
JavaScript
var canvas = document.getElementById('canvas'),
c = canvas.getContext('2d');
function Rectangle(x, y, w, h, color) {
var me = this;
this.x = x,
this.y = y,
this.width = w,
this.height = h,
this.color = color
this.create = function () {
c.fillStyle = this.color;
c.fillRect(me.x, me.y, me.width, me.height);
}
}
var ball = new Rectangle(100, 100, 5, 5, 'blue');
var paddle = new Rectangle(90, 50, 45, 10, 'red');
var deltaY = 1;
function move() {
c.clearRect(0, 0, canvas.height, canvas.width);
ball.y += deltaY;
paddle.create()
ball.create();
if ((ball.y >= paddle.y && ball.y < paddle.y + ball.height &&
ball.x >= paddle.x && ball.x <= paddle.x + paddle.width ) || ball.y < 0) {
deltaY = -deltaY
} else if (ball.y >= canvas.height) {
ball.y = 0; }
}
setInterval(move, 20);