Throwing darts at a drawing
How big is a blob? For a circle there's a formula, but for a doodle there isn't. You can still measure it by throwing darts. Throw them at random over the canvas and count how many land on ink. The share that hits is roughly the share of the canvas the blob covers. This is a Monte Carlo estimate: it works for any shape, and the more darts you throw, the closer it gets.
Throw some darts
The canvas starts with a disc. Paint over it, erase bits of it, or clear it and draw your own shape. Every stroke rethrows the same darts at the new drawing.
Of
The darts on the right land in the same places as long as the seed stays the same, so you can watch single darts turn orange as you paint over them.
How fast it settles
A few darts give a rough answer, and every extra dart refines it. This chart follows the estimate as the darts come in, one at a time, against the exact share (the dashed line).
Throwing four times as many darts only halves the error. The "give or take" above is two
standard errors, 2√(p(1 − p)/n), so about 19 times out of 20 the
estimate lands that close to the truth. With
A dart's estimate of π
The starting disc touches all four sides of its square canvas, so it covers π/4 of it. That makes
four times the hit rate an estimate of π: right now src image.
Things to try
- Halve the disc. Erase half of it with a big eraser. The estimate drops to around 39%.
- Draw a thin line. Thin shapes are hard to hit: with a few hundred darts, a line can get no hits at all, even though it has ink. Drag the darts up and the estimate finds it.
- Rethrow. Click Throw again a few times with 50 darts, then with 5,000. The estimate jumps around a lot less with more darts.
- Start from nothing. Click Blank canvas, which sets
shapeto"". The canvas is cleared, and every dart misses.
How it's built
- The drawing is a variable.
<t-paint name="shape">puts the picture inshapeas a PNG data URL whenever a stroke ends. The board on the right shows that same image, as aPlot.imageunder the darts in a<t-obsplot>. - The pixels come from the canvas. The script registers
throwDartsandinked, which read the canvas's alpha channel through the element'scanvasproperty. They takeshapeas an argument even though they don't decode it: that's what makes the expressions that call them run again after each stroke. The pixels are read once per drawing and shared. - The starting disc is an SVG in the
srcattribute, as a data URL. Clear goes back to it. - Seeded randomness. The darts come from
seed, so painting moves the ink, not the darts. Throw again adds one toseed, and Blank canvas setsshapeto an empty string, which clears the canvas.