JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Application</title>
<style>
/* Ensuring the canvas fills the entire window */
body, html {
margin: 0;
padding: 0;
overflow: hidden;
}
canvas {
display: block;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id="render_canvas"></canvas>
<script src="index.js"></script>
</body>
</html>
JavaScript
const canvas = document.getElementById('render_canvas');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
class Simulation {
constructor() {
this.bodies = [];
}
step(dt) {
// slove forces
for(const body of this.bodies) {
// v = u + f/m * t;
body.linear_velocity[0] += body.force[0] / body.mass * dt;
body.linear_velocity[1] += body.force[1] / body.mass * dt;
// w = wu + to/I * t;
body.angular_velocity += body.torque / body.mmI * dt;
// zero out forces
body.force = [0,0];
body.torque = 0;
}
// integrate position
for(const body of this.bodies) {
// s = s + v * t;
body.pos[0] += body.linear_velocity[0] * dt;
body.pos[1] += body.linear_velocity[1] * dt;
// r = r + w * t;
body.rot += body.angular_velocity*dt;
// wrap angle around [0, 2*PI]
if (body.rot < 0) body.rot += 2 * Math.PI;
if (body.rot >= 2 * Math.PI) body.rot -= 2 * Math.PI;
}
}
newBody(pos, radius, density) {
const body = createBody(pos, radius, density);
this.bodies.push(body);
}
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
// create a new physics body
function createBody(pos, radius, density) {
const area = Math.PI * radius * radius;
const mass = density * area;
// mass moment of intertia
const mmI = mass * radius * radius ;
return {
pos: pos,
rot: 0,
mass: mass,
mmI: mmI,
radius: radius,
force: [0,0],
torque: 0,
linear_velocity: [0, 0],
angular_velocity: 0,
};
}
// applic force at center of mass
function applyForce(body, acc) {
// f = ma;
body.force[0] += body.mass * acc[0];
body.force[1] += body.mass * acc[1];
}
// apply force at arbitrary point, which will result in some...