JavaScript Animation: Orbit Around Latest Parent
บทความนี้อธิบายวิธีการสร้างแอนิเมชันใน JavaScript ซึ่งจุด (circle) จะโคจรรอบ parent ล่าสุด โดยจะโคลนตัวเองทุกๆ 5 วินาทีและโคจรรอบจุดล่าสุดเท่านั้น
แนวคิด
- สร้างจุดเริ่มต้นที่กลางหน้าจอ
- จุดใหม่จะถูกโคลนจากจุดล่าสุดในทุกๆ 5 วินาที
- จุดที่ถูกโคลนจะโคจรรอบจุดล่าสุด (parent) โดยใช้ฟังก์ชัน
Math.cos
และ Math.sin
สำหรับการคำนวณตำแหน่ง
- ใช้
requestAnimationFrame
เพื่ออัปเดตตำแหน่งและวาดจุดใหม่
โค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Orbit Animation</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #121212;
color: white;
}
canvas {
display: block;
margin: auto;
background: black;
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const circles = [];
const cloningInterval = 5000;
class Circle {
constructor(x, y, radius, angle = 0, parent = null) {
this.x = x;
this.y = y;
this.radius = radius;
this.angle = angle;
this.parent = parent;
this.orbitRadius = parent ? 100 : 0;
this.speed = 0.02;
}
update() {
if (this.parent) {
this.angle += this.speed;
this.x = this.parent.x + this.orbitRadius * Math.cos(this.angle);
this.y = this.parent.y + this.orbitRadius * Math.sin(this.angle);
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
}
}
function createInitialCircle() {
const initialX = canvas.width / 2;
const initialY = canvas.height / 2;
const initialRadius = 10;
const initialCircle = new Circle(initialX, initialY, initialRadius);
circles.push(initialCircle);
}
function cloneLastCircle() {
const lastCircle = circles[circles.length - 1];
const newCircle = new Circle(lastCircle.x, lastCircle.y, 10, 0, lastCircle);
circles.push(newCircle);
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circles.forEach(circle => {
circle.update();
circle.draw();
});
requestAnimationFrame(animate);
}
createInitialCircle();
setInterval(cloneLastCircle, cloningInterval);
animate();
</script>
</body>
</html>
ความคิดเห็น
แสดงความคิดเห็น