Matter.js Newton's Cradle — Free Interactive Physics Snippet

Matter.js Newton's Cradle (Drag to Swing) · Animations · Plain HTML, CSS & JS · Live preview

CategoryAnimations

What's included

Features

Constraint strings
Distance constraints to fixed points.
Elastic collisions
restitution: 1 with zero friction.
No rotation
inertia: Infinity keeps energy in the swing.
Stiffer solver
Extra constraint and position iterations.
Custom rendering
Strings, frame and shaded balls in afterRender.
Draggable balls
MouseConstraint with scroll fix.
High-DPI and responsive
CSS-scaled canvas with correct mouse mapping.
Energy loss control
Live air friction slider.

About this UI Snippet

Newton's Cradle in Matter.js — Getting a Physics Engine to Behave Like Physics

Screenshot of the Matter.js Newton's Cradle (Drag to Swing) snippet rendered live

A Newton's cradle is the classic demonstration of conservation of momentum: lift one ball, let it go, and one ball flies out of the other end. It's also a good test of a physics engine, because every small source of energy loss or error shows up immediately as balls drifting together. This snippet builds the cradle from Matter.js bodies and constraints and explains each setting that makes it work.

Strings are constraints

Each ball is a circle hung from a fixed point with Constraint.create({ pointA, bodyB, length, stiffness: 1 }). A constraint keeps two points a fixed distance apart, which is exactly what a taut string does. Increasing engine.constraintIterations makes the solver enforce that distance more accurately every step.

The settings that keep energy in the system

- restitution: 1 makes collisions perfectly elastic. - friction, frictionStatic and frictionAir default to non-zero values; they're set to 0 (air friction is adjustable) so the swing doesn't die immediately. - inertia: Infinity prevents the balls from rotating. Without it, part of each collision's energy turns into spin and the momentum no longer passes cleanly through the row. - A small slop keeps contact overlap tight, which keeps the collision chain crisp.

Custom drawing on top of Matter.Render

Matter's renderer draws the bodies; the afterRender event draws the frame, the strings and shaded metal balls with radial gradients. The context is scaled by the renderer's pixel ratio so drawings stay sharp on high-DPI screens.

Dragging without breaking the page

MouseConstraint lets you grab and pull any ball. It also listens to the mouse wheel and prevents page scrolling while the pointer is over the canvas — a common annoyance in embedded physics demos — so the snippet removes those wheel listeners. The canvas is scaled with CSS, and Matter's mouse maps positions correctly because the renderer records the pixel ratio on the canvas.

Energy loss slider

Raising air friction shows how quickly a real cradle's swing decays.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this snippet into an AI assistant like Claude and ask why inertia: Infinity matters for momentum transfer. Ask it to add a live momentum and energy readout, sound on each collision using the Web Audio API, a seven-ball version, or a slow-motion toggle with engine.timing.timeScale. It can also explain the difference between constraint stiffness and solver iterations.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build an interactive Newton's cradle with Matter.js 0.20 (from a CDN) in plain HTML, CSS and JavaScript on a dark background.

Requirements:
- Five touching circles, each hung from a fixed world point by a distance constraint of equal length (constraints not drawn by Matter).
- Ball options: restitution 1, friction, static friction and air friction 0 (air friction adjustable by a slider), small slop and infinite inertia; raise the engine's constraint and position iterations.
- Buttons to reset or pull the first 1, 2 or 3 balls up along their arc to about 43 degrees and release them; start with one ball pulled unless the user prefers reduced motion.
- Draw a top bar, the strings and radial-gradient metal balls in the renderer's afterRender event, scaled by the pixel ratio.
- A mouse constraint to drag balls, with the wheel listeners removed so the page still scrolls over the canvas, and a responsive canvas scaled with CSS.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.

Source Code

Requires
<div class="nc">
  <div class="nc-top">
    <div>
      <h2>Newton's cradle</h2>
      <p>Drag a ball and let go, or use the buttons. Momentum passes through the row and out the other side.</p>
    </div>
    <div class="nc-btns">
      <button type="button" data-pull="1">Pull 1</button>
      <button type="button" data-pull="2">Pull 2</button>
      <button type="button" data-pull="3">Pull 3</button>
      <button type="button" id="ncReset" class="ghost">Reset</button>
    </div>
  </div>
  <div class="nc-stage" id="ncStage"></div>
  <label class="nc-loss">Energy loss (air friction) <input type="range" id="ncAir" min="0" max="0.004" step="0.0005" value="0.0005"><output id="ncAirOut"></output></label>
</div>

Step by step

How to Use

  1. 1
    Watch it swingOne ball starts swinging on load.
  2. 2
    Pull ballsUse Pull 1, 2 or 3 and watch the same number fly out the other side.
  3. 3
    Drag a ballGrab any ball, pull it along its arc and release.
  4. 4
    Adjust energy lossRaise air friction to see the swing decay.
  5. 5
    ExperimentChange restitution or remove inertia: Infinity in the code and compare.

Real-world uses

Common Use Cases

Physics lessons
Momentum and energy conservation.
Learning Matter.js
Bodies, constraints and body options.
Desk-toy widgets
A calming interactive element.
Portfolio pieces
Show off interactive physics.
Game prototypes
Pendulums and hanging objects.
Related: Matter.js Rope Bridge
Constraints in a chain: Matter.js Rope Bridge You Can Cut.
Related: Matter.js Physics Playground

Got questions?

Frequently Asked Questions

Create a row of touching circles, hang each from a fixed world point with a Constraint of the same length, and set restitution to 1, friction and air friction to 0 and inertia to Infinity on each ball. Then pull the first ball up along its arc and release it.

Friction, air friction, rotation and solver error all remove energy. Set restitution: 1, friction: 0, frictionAir: 0, inertia: Infinity and increase engine.constraintIterations and positionIterations.

MouseConstraint's mouse listens to wheel events and prevents scrolling. Remove them: mouse.element.removeEventListener('mousewheel', mouse.mousewheel) and the same for 'DOMMouseScroll' (and 'wheel').

Listen to the render's afterRender event and draw on render.context. Scale by render.options.pixelRatio first so your drawings line up with the bodies.

No physics engine does exactly, because it steps in discrete time and resolves contacts approximately. With the right settings it's close enough for a convincing cradle, but a long run will slowly drift.