This is very easy way to create bubbles when user click on canvas screen
Here is
screen shot
css
#canvas {
background: #00b4ff;
}
body {
margin: 0;
}
js code
document.addEventListener("DOMContentLoaded", function() {
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const particles = []; // Array to store particles
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.radius = Math.random() * 50;
this.dx = Math.random() * 3;
this.dy = Math.random() * 3;
this.hue = Math.random() * 360; // Random hue for color
}
draw() {
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
context.fillStyle = `hsl(${this.hue}, 100%, 50%)`;
context.fill();
}
move() {
this.x += this.dx;
this.y += this.dy;
// Reverse direction if particle reaches canvas boundaries
if (this.x + this.radius > canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy;
}
}
}
function handleDrawCircle(event) {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX - rect.left;
const mouseY = event.clientY - rect.top;
for (let i = 0; i < 10; i++) { // Create 10 particles on each click
const particle = new Particle(mouseX, mouseY);
particles.push(particle);
}
}
function animate() {
context.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle) => {
particle.move();
particle.draw();
});
requestAnimationFrame(animate);
}
canvas.addEventListener("click", handleDrawCircle);
animate();
});
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="style.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>