JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Rotating Square Ball Bounce</title>
<style>
canvas {
border: 2px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Canvas dimensions
canvas.width = 600;
canvas.height = 400;
// Square properties
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const MAX_SQUARE_HALF_SIZE = Math.floor( (canvas.height/2) / Math.SQRT2 );
const SQUARE_HALF_SIZE = 140; // Safe value within rotation constraints
// Ball properties
const ballRadius = 20;
let ballX = centerX + 50;
let ballY = centerY;
let dx = 3;
let dy = 2;
// Rotation variables
let angle = 0;
const ROTATION_SPEED_DEG_PER_SEC = 1.0; // degrees per second
let lastFrameTime = 0;
function animate(time) {
const deltaTime = (time - lastFrameTime) / 1000;
if(lastFrameTime === 0) {
requestAnimationFrame(animate);
lastFrameTime = time;
return;
}
// Update rotation angle
angle += ROTATION_SPEED_DEG_PER_SEC * Math.PI/180 * deltaTime;
angle %= (2 * Math.PI);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Calculate square boundaries
const squareLeft = centerX - SQUARE_HALF_SIZE;
const squareRight = centerX + SQUARE_HALF_SIZE;
const squareTop = centerY - SQUARE_HALF_SIZE;
const squareBottom = centerY + SQUARE_HALF_SIZE;
// Update ball position with collision checks
let newX = ballX + dx;
let newY = ballY + dy;
// X-axis collision detection and correction
if (newX <= squareLeft + ballRadius) {
newX = squareLeft + ballRadius;
dx *= -1;
} else if (newX >= squareRight - ballRadius) {
newX = squareRight - ballRadius;
dx *= -1;
}
// Y-axis collision detection and correction
if (newY <= squareTop + ballRadius) {
newY = squareTop + ballRadius;
...