//creates a variable called (total points), set equal to 0 var TotalPoints = 0; //creates a variable called (total inside), set equal to 0 var TotalInside = 0; //creates a variable called (canvas), var Canvas; //creates a variable called (total points span), var TotalPointsSpan; //creates a variable called (total inside span), var TotalInsideSpan; //creates a variable called (approx pi span), var ApproxPiSpan; //creates a variable called (context), var Context; //creates a variable called (circle radius), var CircleRadius; //creates a variable called (square area), var SquareArea; //creates a variable called (points input), var PointsInput; // create a function when the page loads ( the function is anonymous) onload = function () { Canvas = document.getElementById("canvas"); PointsInput = document.getElementById("points-input"); TotalPointsSpan = document.getElementById("total-points-span"); TotalInsideSpan = document.getElementById("total-inside-span"); ApproxPiSpan = document.getElementById("approx-pi-span"); Context = Canvas.getContext("2d"); CircleRadius = Canvas.width; SquareArea = Canvas.width * Canvas.width; Canvas.height = Canvas.width; } // creates a function that adds the amount of points specified and assignes each point a color function AddPoints() { var points = Math.floor(PointsInput.value); var inside = 0; for (var i = 0; i < points; i++) { var x = Math.random() * Canvas.width; var y = Math.random() * Canvas.height; var distance = Math.sqrt(x * x + y * y); if (distance < CircleRadius) { inside++; Context.fillStyle = "red"; } else { Context.fillStyle = "blue"; } Context.fillRect(x, y, 1, 1); } //adds the amount of points to the total number of points and adds them to the 'inside' a variable TotalPoints += points; TotalInside += inside; //showing the total amount of points inside the html TotalPointsSpan.innerHTML = TotalPoints; TotalInsideSpan.innerHTML = TotalInside; // approciamates the circle area by dividing the number of total points by the area of the square times the area of inside var approxCircleArea = 4 * SquareArea * TotalInside / TotalPoints; var approxPi = approxCircleArea / SquareArea; ApproxPiSpan.innerHTML = approxPi.toFixed(4); }