javascript 中心角を求める

javascript 中心角を求める

javascriptで、中心角を求めるサンプルコードを記述してます。

環境

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

中心角を求める

中心角は、以下の公式で計算することができます。

中心角 = ( 180 * 弧の長さ ) / ( 円周率 * 半径 )

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

console.log( (180 * 2) / (Math.PI * 1) ) // 114.59155902616465

サンプルコード

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

※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 = (180 * Number(txt.value)) / (Math.PI * 1)
    }

  }

</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-pink-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="text">

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

    </div>

  </div>
</body>

</html>

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