代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>蒙特卡洛方法求解圆周率</title> <style> body { -moz-user-select: none; /*火狐*/ -webkit-user-select: none; /*webkit浏览器*/ -ms-user-select: none; /*IE10*/ -khtml-user-select: none; /*早期浏览器*/ user-select: none; } .container { width: 500px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); height: 700px; box-shadow: 0 0 10px 1px #0000002e; text-align: center; } .btn-container { padding: 0 20px 20px; } .btn-container span { display: inline-block; border: 1px solid transparent; border-radius: 5px; line-height: 1.5; padding: 0 10px; box-sizing: border-box; width: 49%; text-align: center; } .btn-container span:hover { /*background: black;*/ border: 1px solid black; cursor: pointer; } </style> </head> <body> <div class="container"> <h1>蒙特卡洛方法求解圆周率</h1> <canvas id="canvas" width="500" height="500" style="background: bisque"> </canvas> <div class="btn-container"> <span id="btnCalc">增加一万个点</span> <span id="btnClear">清除点</span> <p id="panel">计算结果</p> </div> </div> <script> var canvas = document.getElementById(‘canvas‘); var ctx = canvas.getContext(‘2d‘) ctx.translate(250, 250); //坐标移动到圆心 document.getElementById(‘btnCalc‘).addEventListener(‘click‘, function () { calc() }); document.getElementById(‘btnClear‘).addEventListener(‘click‘, function () { clear() }); /** * 绘制黑色框 */ function square() { ctx.beginPath(); ctx.moveTo(-150, 150); ctx.lineTo(-150, -150); ctx.lineTo(150, -150); ctx.lineTo(150, 150); ctx.closePath(); ctx.stroke() } clear(); var redNum = 0; var blackNum = 0; /** * 绘制圆点 * @param x * @param y * @param r */ function drawCircle(x, y, r) { r = r || 1; ctx.save(); if (x * x + y * y < 150 * 150) { redNum++; ctx.fillStyle = ‘#f00‘ } else { blackNum++; ctx.fillStyle = ‘#000‘ } ctx.beginPath(); ctx.arc(x, y, r, 0, 2 * Math.PI); ctx.fill(); ctx.restore() } /** * 随机增加10000个点 */ function calc() { square(); for (var i = 0; i < 10000; i++) { drawCircle(Math.random() * 300 - 150, Math.random() * 300 - 150); } var span = document.getElementById(‘panel‘); span.innerHTML = ‘在圆形内的共有‘ + redNum + ‘个,‘ + ‘在圆形外的共有‘ + blackNum + ‘单位圆与正方形数量之比是‘ + (redNum / (blackNum + redNum)).toFixed(3) + ‘由此计算值为‘ + ‘<span style="color: red;text-align: left">‘ + (redNum * 4 / (blackNum + redNum)).toFixed(5) + ‘</span>‘ } /** * 清楚绘制的画布 */ function clear() { ctx.beginPath(); ctx.moveTo(-150, 150); ctx.lineTo(-150, -150); ctx.lineTo(150, -150); ctx.lineTo(150, 150); ctx.closePath(); ctx.fillStyle = ‘#fff‘; ctx.fill(); square() } </script> </body> </html>
码云地址:https://gitee.com/Kongdp/CalcPi