First Animated Program

We animate a Monte Carlo integration picking random points within a square. From this we approximate Pi by counting points falling within a circle's area.

We choose points with a square, sides = 2, area = 4. We will draw these points in red when they fall within a circle radius = 1 which we know when x²+y² is within r²

x = rnd() y = rnd() if(x*x + y*y <= 1*1) ...

We'll draw the points on a square html <canvas> large enough to show well on the page.

<canvas id="canvas" width="360" height="360">

We use a 2d api which has functions for choosing colors and drawing dots.

const ctx = window.canvas.getContext("2d") ctx.fillStyle = "red" ctx.fillRect((x+1)*180, (y+1)*180, 1, 1)

We'll repeat the calculation a million times stopping long enough every thousand to calculate and display at the standard refresh rate.

for (let i=0; i<1000000; i++) { if(0 == i%1000) { window.report.innerText = red/i*4 await frame() } }

We save our work in Assets.

pages/first-animated-program

Then show it in a Frame. Jiggle this to restart.

//wiki.ralfbarkow.ch/assets/pages/first-animated-program/circle.html HEIGHT 450

MDN Search Terms canvas getContext fillStyle fillRect await requestAnimationFrame

# Curiosity

The correct behavior of <canvas> seems to require more of the usual doctype and html tag surroundings. When I couldn't make a really small program work I turned to the mdn example that did work before experimentally disassembling that. mdn

Unlike our results, the decimal 𝝅 has no repeating digits. When we compute the ratio of areas we are asking for repeating decimals and find quite a variety of new sequences with each run. wikipedia

~