javascript 円周の長さを求める

javascript 円周の長さを求める

javascriptで、円周の長さを求めるサンプルコードを記述してます。円周率を「Math.PI」で取得して、円周の長さの公式を演算することで求めることができます。

環境

  • OS windows11 home
  • Apache 2.4.43
  • ブラウザ chrome 108.0.5359.72

円周の長さ

円周の長さは、以下の公式で計算することができます。

円周の長さ = 2 * 半径 * 円周率

円周率は「Math.PI」で取得できるので、以下のように求めることが可能です。
※ここでは半径が「10」の円周の長さを計算してます。

console.log( 2 * 10 * Math.PI ) // 62.83185307179586

サンプルコード

以下は、実行ボタンをクリックすると、テキストフォームに入力した数値を半径として円周を求めて、出力するだけのサンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => {
      foo.innerHTML = 2 * Number(txt.value) * Math.PI
    }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-parplu-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input
        class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        id="txt" type="txt">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-yellow-500 text-yellow-700 font-semibold hover:text-white py-2 px-4 border border-yellow-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

計算されて出力されていることが確認できます。