-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (71 loc) · 2.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let insidePointsCounted = document.getElementById('insidePoints');
let totalPointsCounted = document.getElementById('totalPoints');
let pi = document.getElementById('pi');
let width = canvas.width;
let height = canvas.height;
let radius = (width <= height) ? width : height;
//Draw quarterCirle
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI);
ctx.stroke();
let pointsInsideCircle = 0;
let totalPoints = 0;
let maxRange = 1 + Number.EPSILON;
let outsidePointsQueue = [];
let insidePointsQueue = [];
let maxNumberOfPoints = 400;
let pointSize = 4;
function computePoint() {
let randomX = Math.random() * maxRange;
let randomY = Math.random() * maxRange;
let distanceSquared = Math.pow(randomX, 2) + Math.pow(randomY, 2);
let xPoint = (randomX * radius);
let yPoint = (randomY * radius);
if(distanceSquared < 1) {
pointsInsideCircle++;
insidePointsQueue.push({x: xPoint, y: yPoint});
if(insidePointsQueue.length > maxNumberOfPoints) {
let oldPoint = insidePointsQueue.shift();
ctx.fillStyle = "#D5FED1";
ctx.fillRect(oldPoint.x, oldPoint.y, pointSize, pointSize);
}
ctx.fillStyle = "#17EA00";
} else {
outsidePointsQueue.push({x: xPoint, y: yPoint});
if(outsidePointsQueue.length > maxNumberOfPoints) {
let oldPoint = outsidePointsQueue.shift();
ctx.fillStyle = "#FEE1E1";
ctx.fillRect(oldPoint.x, oldPoint.y, pointSize, pointSize);
}
ctx.fillStyle = "#FF0000";
}
totalPoints++;
ctx.fillRect(xPoint, yPoint, pointSize, pointSize);
insidePointsCounted.innerHTML = 'Points Inside = ' + pointsInsideCircle;
totalPointsCounted.innerHTML = 'Total Points = ' + totalPoints;
pi.innerHTML = 'PI = ' + (4 * (pointsInsideCircle / totalPoints));
}
function refreshCircle() {
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI);
ctx.stroke();
}
let play = false;
let intervalIDCompute;
let intervalIDRefresh;
let startButton = document.getElementById('startButton');
startButton.addEventListener('click', () => {
if(!play) {
intervalIDCompute = setInterval(computePoint, 30);
intervalIDRefresh = setInterval(refreshCircle, 50000);
startButton.innerHTML = 'Pause Simulation';
} else {
clearInterval(intervalIDCompute);
clearInterval(intervalIDRefresh);
startButton.innerHTML = 'Start Simulation';
}
play = !play;
});