My project for course: Creative Coding 2.0 in JS: Animation, Sound, & Color
di Diana-Georgiana Dinu @dianadinu557
- 293
- 1
- 0
<html>
<head>
<title>Particle Interaction</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<script>
// Particle class
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 5;
this.speed = 2;
}
update(mouseX, mouseY) {
const dx = this.x - mouseX;
const dy = this.y - mouseY;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 100) {
const angle = Math.atan2(dy, dx);
this.x += Math.cos(angle) * this.speed;
this.y += Math.sin(angle) * this.speed;
}
this.draw();
}
draw() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = 'black';
ctx.fill();
ctx.closePath();
}
}
// Initialize particles
const particles = [];
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
particles.push(new Particle(x, y));
}
// Mouse move event handler
function onMouseMove(event) {
const canvas = document.getElementById('canvas');
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
for (let i = 0; i < particles.length; i++) {
particles[i].update(mouseX, mouseY);
}
}
// Attach mouse move event listener to canvas
const canvas = document.getElementById('canvas');
canvas.addEventListener('mousemove', onMouseMove);
// Render loop
function animate() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
particles[i].update(mouseX, mouseY);
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
0 commenti
Accedi o iscriviti gratuitamente per commentare