Newton's Cradle Tutorial
Briefly

Newton's Cradle Tutorial
"Step 2: Initialize Canvas and Constants Set up the canvas context and define the physical parameters of your cradle: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const numBalls = 5; // Number of balls in cradle const ballRadius = 20; // Radius of each ball const stringLength = 150; // Length of pendulum string const frameY = 50; // Y position of top frame const spacing = ballRadius * 2 + 2; // Space between balls const centerX = canvas.width / 2; // Center of canvas let balls = []; let dragging = null; // Track which ball is being dragged"
"Step 3: Create the Ball Class Ball Properties Each ball is a pendulum with an anchor point, angle, and velocity: class Ball { constructor(index) { this.index = index; this.anchorX = centerX + (index - 2) * spacing; this.anchorY = frameY; this.angle = 0; // Current angle from vertical this.velocity = 0; // Angular velocity this.mass = 1; this.stringLength = stringLength; } } Calculate Position Convert polar coordinates (angle) to Cartesian coordinates (x, y): get x() { return this.anchorX + Math.sin(this.angle) * thi"
A canvas element and control buttons provide the user interface for starting swings and resetting the simulation. The script initializes the canvas context and defines physical parameters such as number of balls, ball radius, string length, frame position, spacing, and center coordinates. Each ball is modeled as a pendulum with an anchor point, angle, angular velocity, mass, and string length. Positions convert polar coordinates to Cartesian coordinates using trigonometric functions of the angle. The simulation implements pendulum physics, collision detection, momentum transfer, and mouse/touch event handling for interactive dragging and swinging. An animation loop renders strings and balls and updates physics each frame.
Read at Slicker
Unable to calculate read time
[
|
]