JSFiddle - React, Tailwind, and code Playground
by Amatewasu
HTML
<canvas id="playground" width="800" height="600"></canvas>
<button onclick="deleteRandomBrick()">
Delete a brick
</button>
JavaScript
var canvas = document.querySelector("#playground");
var ctx = canvas.getContext("2d");
const W = canvas.width;
const H = canvas.height;
const g = 9.81; // m.s⁻² in France
const FRICTION_FACTOR = 0.8;
const GROUND_LEVEL = H-H/4;
var balls = [];
var bricks = [
{ x: 400, y: 380, w: 20, h: 10, angle: 0, speed: { x: 0, y:0, angle: 0 } },
{ x: 415, y: 340, w: 20, h: 10, angle: 0, speed: { x: 0, y:0, angle: 0 } },
{ x: 420, y: 320, w: 20, h: 10, angle: 0, speed: { x: 0, y:0, angle: 0 } },
{ x: 425, y: 300, w: 20, h: 10, angle: 0, speed: { x: 0, y:0, angle: 0 } },
{ x: 430, y: 250, w: 30, h: 15, angle: 0, speed: { x: 0, y:0, angle: 0 } },
{ x: 440, y: 200, w: 40, h: 20, angle: 0, speed: { x: 0, y:0, angle: 0 } }
];
var collisions = [];
var lastCompute = Date.now();
var lastLog = Date.now();
var mousePos = { x: 0, y: 0 };
var fixedBall = false;
var startPos = {
x: 100,
y: Math.floor(H/2)
};
function draw (){
ctx.fillStyle = "black";
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = "green";
ctx.fillRect(0, GROUND_LEVEL, W, H-GROUND_LEVEL)
var ball;
for (var i = 0; i < balls.length; i++){
ball = balls[i];
ctx.fillStyle = ball.color;
ctx.beginPath();
ctx.arc(Math.floor(ball.x), Math.floor(ball.y), ball.radius, 0, 2*Math.PI);
ctx.fill();
}
ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
ctx.beginPath();
ctx.arc(mousePos.x, mousePos.y, 5, 0, 2*Math.PI);
ctx.fill();
if (fixedBall){
var d = Math.sqrt((startPos.x-mousePos.x)*(startPos.x-mousePos.x) + (startPos.y-mousePos.y)*(startPos.y-mousePos.y));
var dirX = (startPos.x - mousePos.x);
var dirY = (startPos.y - mousePos.y);
var norm = Math.sqrt(dirX*dirX + dirY*dirY);
dirX /= norm;
dirY /= norm;
d = d > 50 ? 50 : d;
var to = {
x: startPos.x + dirX*d,
y: startPos.y + dirY*d
};
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.moveTo(startPos.x, startPos.y);
ctx.lineTo(to.x,...