Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo mảng tọa độ tròn (Circle Coordinates) trong JavaScript


Tính tọa độ các điểm trên đường tròn: x = centerX + r * cos(2π * i/steps), y = centerY + r * sin(2π * i/steps). Dùng cho animation, canvas, game.

Ví dụ

Tạo 5 điểm trên đường tròn bán kính 10, tâm (4,4):

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Circle coordinates</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-weight: 500; font-size: 18px; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Tạo mảng tọa độ tròn (Circle Coordinates)</h1>
  <div class="result"></div>
  <br />
  <button class="Btn">TẠO TỌA ĐỘ</button>
  <h3>Nhấn nút để sinh 5 điểm trên đường tròn r=10, tâm (4,4)</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btn = document.querySelector(".Btn");
    const xCoords = [], yCoords = [];
    function circleCoordinates(radius, steps, centerX, centerY) {
      for (let i = 0; i < steps; i++) {
        const angle = 2 * Math.PI * (i / steps);
        xCoords.push(centerX + radius * Math.cos(angle));
        yCoords.push(centerY + radius * Math.sin(angle));
      }
    }
    btn.addEventListener("click", () => {
      circleCoordinates(10, 5, 4, 4);
      resEle.innerHTML = 'Tọa độ 5 điểm trên đường tròn:<br>';
      for (let i = 0; i < xCoords.length; i++) {
        resEle.innerHTML += `X = ${xCoords[i].toFixed(2)} : Y = ${yCoords[i].toFixed(2)}<br>`;
      }
    });
  </script>
</body>
</html>

Kết quả

5 cặp tọa độ (X, Y) phân bố đều trên đường tròn.

Ứng dụng: Vẽ đa giác đều, animation chuyển động tròn, radar chart.