JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<h3>PI approximation using Monte Carlo method</h3>
<div class="wrapper">
<div id="points">ukupno tacaka: 0</div>
<div id="pi-approx">aproksimacija broja PI: 0</div>
</div>
<canvas id="canvas" width="400" height="400" style="border: 1px solid #efefef">Your browser doesn't support html5 canvas</canvas>
</body>
</html>
JavaScript
var cnv = document.getElementById('canvas');
var a = 400;
var point_size = 3;
var points_to_generate = 1000000;
var points_generated = 0;
var rand_x = 0,
rand_y = 0,
total_in = 0,
total = 0;
var ctx = cnv.getContext('2d');
ctx.fillStyle = "#f1f1f1";
ctx.fillRect(0, 0, a, a);
ctx.strokeStyle = "#f2ef24";
ctx.beginPath();
ctx.arc(0, 0, a, 0, 2 * Math.PI);
ctx.stroke();
function graph() {
if (points_generated > points_to_generate) clearInterval(timer_id);
points_generated++;
rand_x = Math.floor(Math.random() * a) + 1;
rand_y = Math.floor(Math.random() * a) + 1;
if (rand_x * rand_x + rand_y * rand_y <= a * a) {
total_in++;
ctx.fillStyle = "#67ff24";
ctx.fillRect(rand_x, rand_y, point_size, point_size);
} else {
ctx.fillStyle = "#ff2324";
ctx.fillRect(rand_x, rand_y, point_size, point_size);
}
total++;
$('#points').html('total points: ' + total);
$('#pi-approx').html('approximation of PI: ' + total_in / (total + 0.0) * 4);
}
var timer_id = setInterval(graph, 3);