JSFiddle - React, Tailwind, and code Playground
by Yaroslav Samardak
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="dpi" style="height: 1in; width: 1in; left: 100%; position: fixed; top: 100%;pointer-events:none"></div>
<div id="out">Out</div>
<canvas id="canvas" width="600" height="600"></canvas>
</body>
</html>
CSS
canvas {
width: 100%;
height: 80vh;
background: gray
}
JavaScript
window.onload = () => {
const out = document.getElementById('out')
const ctx = document.getElementById('canvas').getContext('2d');
var dpi = (document.getElementById('dpi').offsetWidth * 2.54)
const m = 1 / dpi;
const w = 600, h = 600, r = 5;
const box = [10, 10, h - 10, w - 10]
const g = 9.8 * m;
const speed = { x: -1350 * m, y: -560 * m }
const friction = 0.95
const position = {x: (box[2] - box[0]) / 2, y: (box[2] - box[0]) / 2 }
let i = 0;
function draw(timeDelta) {
ctx.clearRect(0, 0, 600, 600)
ctx.strokeStyle = "black";
speed.y += (g * m * timeDelta) || 0
// speed.x += (m * timeDelta) || 0
position.y = Math.max(box[1] + r, Math.min(box[3] - r, position.y + speed.y));
position.x = Math.max(box[0] + r, Math.min(box[2] - r, position.x + speed.x));
if (position.y + r >= box[3] || position.y - r <= box[1]) {
speed.y = -(speed.y * friction)
speed.x = speed.x * friction
}
if (position.x + r >= box[2] || position.x - r <= box[0]) {
out.innerText = ++i
speed.y = speed.y * friction
speed.x = -(speed.x * friction)
}
//out.innerText = `${Math.round(position.y)}, ${Math.round(position.x)}, ${Math.round(speed.y * 1000) / 1000}, ${Math.round(speed.x * 1000) / 1000}`
ctx.beginPath();
ctx.arc(position.x, position.y, r, 0, Math.PI * 2, true);
ctx.fill();
ctx.lineWidth = 1;
ctx.moveTo(box[0], box[1]);
ctx.lineTo(box[2], box[1]);
ctx.lineTo(box[2], box[3]);
ctx.lineTo(box[0], box[3]);
ctx.lineTo(box[0], box[1]);
ctx.strokeStyle = "white";
ctx.stroke();
window.requestAnimationFrame(draw)
}
draw();
}