Matter.js Drag-and-Throw Physics Playground — Free Interactive Snippet

Matter.js Drag-and-Throw Physics Playground · Animations · Plain HTML, CSS & JS · Live preview

CategoryAnimations

What's included

Features

Engine, render and runner
The standard Matter.js setup.
Four spawn types
Rounded boxes, balls, hexagons and stacks.
Drag and throw
MouseConstraint with scroll fix.
Gravity presets
Any direction, including zero-G.
Slow motion
engine.timing.timeScale.
Double-click spawning
Query.point avoids spawning on bodies.
Live stats
Body count and steps per second.
Clear button
Removes all dynamic bodies.

About this UI Snippet

A Matter.js Playground — The Core API in One Toy

Screenshot of the Matter.js Drag-and-Throw Physics Playground snippet rendered live

The fastest way to understand a physics engine is to throw things around in it. This playground wraps the parts of Matter.js you use in nearly every project — creating bodies, walls, mouse dragging, gravity and time — into one small toy, with each control mapped to a single API.

Engine, renderer, runner

Engine.create() holds the world and steps the simulation. Render.create() draws it on a canvas (wireframes: false enables colours), and Runner.run() advances the engine every animation frame. Everything added with Composite.add(engine.world, ...) becomes part of the simulation.

Bodies and composites

Bodies.rectangle (with a chamfer for rounded corners), Bodies.circle and Bodies.polygon create single bodies with options such as restitution (bounciness) and friction. Composites.stack lays out a grid of bodies from a callback — the "Stack" button drops twelve boxes at once. Walls are static bodies placed just outside the visible area.

Gravity is just a vector

engine.gravity.x and .y set the direction. Up, sideways, zero and a weak moon gravity are all one assignment each. (If you enable sleeping for performance, resting bodies must be woken to feel a new gravity.)

Time scale

engine.timing.timeScale slows or speeds the whole simulation without changing its behaviour: 0.2 is smooth slow motion, which is handy for inspecting collisions.

Dragging and spawning

MouseConstraint lets you grab and throw any body; its wheel listeners are removed so the page still scrolls over the canvas. Double-clicking empty space uses Query.point to check that nothing is under the cursor, then drops a random shape there.

Watching performance

The stats line counts non-static bodies and simulation steps per second, so you can see how the engine copes as you add dozens of stacks.

Build with AI

Build, Understand, Optimize, and Extend It With AI

Paste this playground into an AI assistant like Claude and ask it to explain each Matter.js object it uses. Ask it to add shape presets like dominoes or a Newton's cradle, device-tilt gravity with the DeviceOrientation API, a "freeze" toggle using isStatic, or saving and restoring the scene. It can also help you find the body count where performance drops on mobile.

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 a Matter.js 0.20 physics playground (from a CDN) in plain HTML, CSS and JavaScript.

Requirements:
- A responsive canvas with invisible walls just outside the edges and one angled static platform.
- Buttons to add a rounded box, a ball, a hexagon or a 4×3 stack of boxes (Composites.stack) at a random x near the top, each with a colour from a palette; drop six shapes on load.
- A gravity select (down, up, right, zero, moon) that sets engine.gravity, and a speed slider that sets engine.timing.timeScale from 0.1 to 1.5.
- Drag and throw bodies with a mouse constraint, removing its wheel listeners so the page scrolls.
- Double-click empty space to spawn a random shape there, using Query.point to ignore clicks on existing bodies.
- A clear button that removes dynamic bodies, and a stats line with the body count and steps per second.

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="pg">
  <div class="pg-bar">
    <div class="pg-group" role="group" aria-label="Add shapes">
      <button type="button" data-add="box">+ Box</button>
      <button type="button" data-add="ball">+ Ball</button>
      <button type="button" data-add="poly">+ Hexagon</button>
      <button type="button" data-add="stack">+ Stack</button>
    </div>
    <label>Gravity <select id="pgGravity"><option value="0,1">Down</option><option value="0,-1">Up</option><option value="1,0">Right</option><option value="0,0">Zero-G</option><option value="0,0.3">Moon</option></select></label>
    <label>Speed <input type="range" id="pgSpeed" min="0.1" max="1.5" step="0.1" value="1"><output id="pgSpeedOut">1.0×</output></label>
    <button type="button" id="pgClear" class="ghost">Clear</button>
    <span class="pg-stats" id="pgStats"></span>
  </div>
  <div class="pg-stage" id="pgStage"></div>
  <p class="pg-hint">Drag shapes to throw them · double-click empty space to drop a random shape</p>
</div>

Step by step

How to Use

  1. 1
    Add shapesUse the buttons or double-click empty space.
  2. 2
    Throw themDrag any shape and release while moving.
  3. 3
    Change gravityDown, up, right, zero-G or moon.
  4. 4
    Slow timeDrag Speed to 0.2× for slow motion.
  5. 5
    Stress testAdd stacks and watch the body count and steps per second.

Real-world uses

Common Use Cases

Learning Matter.js
Every core concept in one file.
Game prototyping
A starting sandbox for physics games.
Interactive backgrounds
Playful elements for landing pages.
Teaching physics
Gravity and collisions you can poke.
Performance testing
See how many bodies a device handles.
Related: Matter.js Newton's Cradle
Constraints and elastic collisions: Matter.js Newton's Cradle (Drag to Swing).
Related: Matter.js Falling Tags
Physics text chips: Matter.js Falling Tags.

Got questions?

Frequently Asked Questions

Create an engine with Engine.create(), a renderer with Render.create({ element, engine, options }), add bodies with Composite.add(engine.world, bodies), then start Render.run(render) and Runner.run(Runner.create(), engine).

Set engine.gravity.x and engine.gravity.y. For example x: 0, y: -1 makes things fall upward, and 0, 0 gives zero gravity. engine.gravity.scale adjusts overall strength.

Set engine.timing.timeScale to a value below 1, such as 0.2. The simulation runs slower but behaves the same way.

Create a Mouse on the canvas and a MouseConstraint for the engine, add the constraint to the world, and set render.mouse. Remove the mouse's wheel listeners if the page must scroll over the canvas.

Use Query.point(bodies, point), which returns every body containing that point.