원 위의 좌표를 구하는 핵심은 삼각함수입니다. 반지름과 중심 좌표가 주어졌을 때, Math.cos와 Math.sin을 사용하면 원주 위의 각 점의 X, Y 좌표를 쉽게 계산할 수 있습니다.
각도는 2π(360도)를 원하는 단계 수(steps)로 나눈 비율로 계산하며, 이렇게 구한 좌표들을 각각 배열에 순차적으로 저장합니다.
예제
다음은 JavaScript에서 원의 좌표를 계산하여 배열에 저장하는 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</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>Circle coordinates to array</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to generate the circle coordinates</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let xCoords = [];
let yCoords = [];
function circleCoordinates(radius, steps, centerX, centerY) {
for (let i = 0; i < steps; i++) {
xCoords.push(centerX + radius * Math.cos(2 * Math.PI * (i / steps)));
yCoords.push(centerY + radius * Math.sin(2 * Math.PI * (i / steps)));
}
}
BtnEle.addEventListener("click", () => {
circleCoordinates(10, 5, 4, 4);
resEle.innerHTML = "Coordinates for circle are: <br>";
for (let i = 0; i < xCoords.length; i++) {
resEle.innerHTML +=
"X = " + xCoords[i] + " : Y = " + yCoords[i] + "<br>";
}
});
</script>
</body>
</html>코드 설명
circleCoordinates(radius, steps, centerX, centerY) 함수는 네 개의 매개변수를 받습니다.
- radius: 원의 반지름
- steps: 원주 위에서 좌표를 추출할 점의 개수
- centerX, centerY: 원의 중심 좌표
반복문 안에서 i / steps 비율에 2π를 곱해 라디안 각도를 만들고, 여기에 코사인과 사인을 적용하여 X좌표와 Y좌표를 각각 xCoords, yCoords 배열에 push합니다.
출력 결과
페이지가 로드되면 다음과 같은 초기 화면이 표시됩니다.

'CLICK HERE' 버튼을 클릭하면 계산된 원의 좌표가 화면에 출력됩니다.

이 방식은 캔버스(canvas)에 원을 그리거나, 애니메이션에서 객체를 원형 경로로 움직일 때 등 다양한 상황에서 활용할 수 있습니다.