← Mike Cogliandro

Napkin Physics

Draw a ramp on paper. Show it to your camera. Watch the balls roll.

Everything runs in your browser. Your camera image never leaves your device.

Hold the paper flat and fill the dashed box, then press Freeze.
No sketch yet

Click or tap anywhere on the sketch to drop a ball.

What the computer sees

A camera doesn’t give a computer lines or ramps. It gives a grid of numbers. These five steps turn a messy photo of a napkin into a few dozen straight walls a physics engine can use. The thumbnails update with your own sketch.

Step 1

The photo

Hundreds of thousands of colored dots, with shadows, smudges and paper texture mixed in.

imread
Step 2

Color removed

To find ink, only brightness matters, so each dot becomes one number from black to white.

cvtColor
Step 3

Ink found

Each dot is compared with its neighbors, not the whole page, so a shadow across the paper doesn’t fool it.

adaptiveThreshold
Step 4

Gaps healed

Small breaks in pen strokes are closed and lines are thickened slightly so balls can’t sneak through.

morphologyEx + dilate
Step 5

Walls built

Each ink shape is traced and simplified to a handful of corners. Specks too small to matter are thrown out.

findContours + approxPolyDP

Why it works this way

The obvious approach is to call anything darker than a fixed gray “ink.” It fails the moment a shadow falls across the page, because the shaded paper becomes darker than the ink on the bright side. Comparing each spot only with its own neighborhood solves that, and it’s the same idea document scanners use.

Why simplify the shapes?

A traced pen line can have thousands of tiny steps along its edge. A physics engine checks every ball against every wall many times a second, so fewer walls means smoother motion. Turning up corner detail shows the trade-off: more accurate walls, more work for the computer.