JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="genuary" width="256" height="256"></canvas>
JavaScript
const canvas = document.getElementById("genuary");
const ctx = canvas.getContext("2d");
const rectSize = 16;
const numRectanglesX = canvas.width / rectSize;
const numRectanglesY = canvas.height / rectSize;
let ball1 = {
x: 192,
y: 32,
xSpeed: 3,
ySpeed: 2,
color: 'purple',
};
let ball2 = {
x: 32,
y: 192,
xSpeed: 3,
ySpeed: 2,
color: 'orange',
};
let bricks = [];
for (let c = 0; c < numRectanglesX; c++) {
bricks[c] = [];
for (let r = 0; r < numRectanglesY; r++) {
const color = (c < numRectanglesX / 2) ? 'purple' : 'orange';
bricks[c][r] = {
x: c * rectSize,
y: r * rectSize,
color
};
}
}
function drawBricks() {
for (let c = 0; c < numRectanglesX; c++) {
for (let r = 0; r < numRectanglesY; r++) {
const currentBrick = bricks[c][r];
ctx.fillStyle = currentBrick.color;
ctx.fillRect(currentBrick.x, currentBrick.y, rectSize, rectSize);
}
}
}
function drawBall(ball) {
ctx.fillStyle = ball.color;
ctx.fillRect(ball.x, ball.y, rectSize, rectSize);
}
function collisionDetection(ball) {
for (let c = 0; c < numRectanglesX; c++) {
for (let r = 0; r < numRectanglesY; r++) {
const currentBrick = bricks[c][r];
const ballCenterX = ball.x + rectSize / 2;
const ballCenterY = ball.y + rectSize / 2;
if (
ballCenterX > currentBrick.x &&
ballCenterX < currentBrick.x + rectSize &&
ballCenterY > currentBrick.y &&
ballCenterY < currentBrick.y + rectSize &&
currentBrick.color === ball.color
) {
currentBrick.color = currentBrick.color === 'orange' ? 'purple' : 'orange';
ball.xSpeed *= -1;
}
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBricks();
drawBall(ball1);
drawBall(ball2);
collisionDetection(ball1);
collisionDetection(ball2);
ball1.x += ball1.xSpeed;
ball1.y += ball1.ySpeed;
// Wall collision
if (ball1.x + rectSize > canvas.width ||...