자바스크립트로 컬러풀한 행성 애니메이션 구현하기
안녕하세요! 이번에는 자바스크립트를 사용하여 컬러풀한 행성 애니메이션을 구현하는 방법에 대해 알아보겠습니다.
1. HTML 준비하기
먼저, HTML 파일을 생성하고 <canvas>
요소를 추가합니다. 행성 애니메이션을 그리기 위해 캔버스를 사용할 것입니다.
<canvas id="canvas"></canvas>
2. 자바스크립트 코드 작성하기
다음으로, 자바스크립트 파일을 생성하고 행성 애니메이션을 구현할 코드를 작성합니다.
// 캔버스 요소 가져오기
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 화면 크기에 맞게 캔버스 크기 설정
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 행성 객체 생성
class Planet {
constructor(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.speed = Math.random() * 2 + 1;
this.angle = Math.random() * 360;
}
// 행성 그리기 메서드
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
// 행성 움직이기 메서드
move() {
this.x += Math.cos(this.angle) * this.speed;
this.y += Math.sin(this.angle) * this.speed;
// 캔버스 경계 체크
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.angle = Math.atan2(Math.sin(this.angle), -Math.cos(this.angle));
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.angle = Math.atan2(-Math.sin(this.angle), Math.cos(this.angle));
}
}
// 애니메이션 메서드
animate() {
this.move();
this.draw();
}
}
// 행성 객체들을 저장할 배열 생성
const planets = [];
// 행성 생성 및 배열에 추가
for (let i = 0; i < 10; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const radius = Math.random() * 30 + 10;
const color = `hsl(${Math.random() * 360}, 50%, 50%)`;
const planet = new Planet(x, y, radius, color);
planets.push(planet);
}
// 애니메이션 프레임 실행
function animate() {
// 캔버스 초기화
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 모든 행성 애니메이션 실행
planets.forEach((planet) => {
planet.animate();
});
// 다음 프레임 실행
requestAnimationFrame(animate);
}
// 애니메이션 시작
animate();
3. 실행하기
코드 작성이 끝났다면 작성한 HTML 파일을 열어보세요. 컬러풀한 행성들이 움직이며 애니메이션을 구현한 것을 확인할 수 있을 것입니다.
마치며
이번 포스트에서는 자바스크립트를 사용하여 컬러풀한 행성 애니메이션을 구현하는 방법에 대해 알아보았습니다. 이를 응용하여 다양한 애니메이션 효과를 구현해볼 수 있으니 자유롭게 실험해보세요!