JSFiddle - React, Tailwind, and code Playground

by itbeard

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bouncing Yellow Ball in Rotating Square</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
            background-color: #1a1a1a;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        canvas {
            border: 2px solid #fff;
            box-shadow: 0 0 20px rgba(255, 255, 255, 0.5);
        }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        // Get canvas and context
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        
        // Set canvas size
        canvas.width = 600;
        canvas.height = 600;
        
        // Ball properties
        const ball = {
            x: canvas.width / 2,
            y: canvas.height / 2,
            radius: 15,
            vx: 3,       // initial x velocity
            vy: -2,      // initial y velocity
            color: 'yellow',
            gravity: 0.25,
            damping: 0.8, // air resistance
            elasticity: 0.8, // bounciness
            friction: 0.999  // friction with surface
        };
        
        // Square properties
        const square = {
            cx: canvas.width / 2,      // center x
            cy: canvas.height / 2,    // center y
            side: 300,                // side length
            angle: 0,                 // current rotation angle (radians)
            rotationSpeed: 0.015,     // rotation speed
            color: '#4CAF50',         // green color for square
            strokeWidth: 8
        };
        
        // For collision detection
        let lastBallPosition = {...ball};
        const minDistance = 10; // minimum distance to prevent...