Q&A
実現したいこと
htmlだけでモンテカルロ法を使った円周率の計算をしようとしています。
前提
ボタンを押すとなります。
発生している問題・エラーメッセージ
Uncaught TypeError: canvas.getContext is not a function at start ((index):25:32) at HTMLButtonElement.onclick ((index):17:31) start @ (index):25 onclick @ (index):17
該当のソースコード
html
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>モンティ・カルロ法による円周率の計算</title> 5 <style> 6 #canvas { 7 position: absolute; 8 top: 50%; 9 left: 50%; 10 transform: translate(-50%, -50%); 11 } 12 </style> 13 </head> 14 <body> 15 <h1>モンティ・カルロ法による円周率の計算</h1> 16 <div id="canvas"></div> 17 <button onclick="start()">計算開始</button> 18 <p id="result"></p> 19 20 <script> 21 function start() { 22 const canvas = document.getElementById("canvas"); 23 const width = 500; 24 const height = 500; 25 const context = canvas.getContext("2d"); 26 canvas.width = width; 27 canvas.height = height; 28 context.fillStyle = "#FFFFFF"; 29 context.fillRect(0, 0, width, height); 30 context.strokeStyle = "#000000"; 31 context.beginPath(); 32 context.arc(width / 2, height / 2, width / 2, 0, 2 * Math.PI); 33 context.stroke(); 34 35 let count = 0; 36 let total = 0; 37 const n = 1000000; 38 for (let i = 0; i < n; i++) { 39 const x = Math.random() * width; 40 const y = Math.random() * height; 41 const dx = x - width / 2; 42 const dy = y - height / 2; 43 if (dx * dx + dy * dy < (width / 2) * (width / 2)) { 44 context.fillStyle = "#000000"; 45 count++; 46 } else { 47 context.fillStyle = "#00FF00"; 48 } 49 context.beginPath(); 50 context.arc(x, y, 1, 0, 2 * Math.PI); 51 context.fill(); 52 total++; 53 } 54 55 const pi = (4 * count) / total; 56 document.getElementById("result").textContent = `π ≈ ${pi}`; 57 } 58 </script> 59 </body> 60</html> 61
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2023/03/16 09:07