webdevpuneet.com

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

Copy & paste

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>

Extend with AI

Take This Snippet Further With AI

The AI prompt for this one is for Patreon supporters ($3 a month, 7 days free), along with a site with no ads. Supporters enter the passcode once and it is remembered in this browser.

· Become a supporter

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.

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
Understand every core concept in one file, from the engine, renderer and runner to walls, bodies and a MouseConstraint with a scroll fix.
Physics game prototyping
Start from a sandbox that already spawns rounded boxes, balls, hexagons and stacks, then add goals and rules around it.
Gravity and time experiments
Switch gravity between down, up, sideways, zero-G and moon presets, and slow time with engine.timing.timeScale to study collisions.
Playful interactive backgrounds
Add throwable objects to a landing page, where visitors can double-click to spawn more and drag anything around.
Device performance testing
See how many bodies a phone or laptop can simulate before frames drop, by adding stacks until the playground slows.
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.