Sure! Below is a complete HTML file that creates a soothing visual and auditory experience to help you fall asleep. It features colorful particles gracefully moving across the screen with trailing effects and plays a continuous ambient sound using the Web Audio API.
Features:
- Canvas Animation: Utilizes HTML5 Canvas to render colorful particles that move slowly, leaving gentle trails behind them.
- Ambient Sound: Generates a calming white noise using the Web Audio API to aid relaxation and sleep.
- Responsive Design: Adjusts the canvas size based on the browser window dimensions.
How It Works:
- Particles: Each particle has properties like position, velocity, size, and color. They move slowly across the screen, and their trails are created by drawing semi-transparent rectangles over the canvas on each frame, giving a fading trail effect.
- Sound: The Web Audio API creates a white noise oscillator connected to a gain node for volume control. The noise plays continuously in a loop.
Usage:
- Save the Code: Copy the code below into a text editor and save it with a
.html extension, for example, sleep-aid.html.
- Open in Browser: Double-click the saved file or open it through your web browser to enjoy the visual and auditory experience.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sleep Aid - Relaxing Particles and Ambient Sound</title>
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #000; /* Start with black background */
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="particlesCanvas"></canvas>
<script>
// === Canvas Setup ===
const canvas = document.getElementById('particlesCanvas');
const ctx = canvas.getContext('2d');
let width = window.innerWidth;
let height = window.innerHeight;
canvas.width = width;
canvas.height = height;
// Handle window resize
window.addEventListener('resize', () => {
width = window.innerWidth;
height = window.innerHeight;
canvas.width = width;
canvas.height = height;
});
// === Particle Class ===
class Particle {
constructor() {
this.reset();
}
reset() {
this.x = Math.random() * width;
this.y = Math.random() * height;
const angle = Math.random() * 2 * Math.PI;
const speed = 0.2 + Math.random() * 0.3;
this.vx = Math.cos(angle) * speed;
this.vy = Math.sin(angle) * speed;
this.size = 2 + Math.random() * 3;
this.color = `hsl(${Math.floor(Math.random() * 360)}, 60%, 70%)`;
this.alpha = 0.7;
}
update() {
this.x += this.vx;
this.y += this.vy;
// Wrap around the edges
if (this.x > width) this.x = 0;
if (this.x < 0) this.x = width;
if (this.y > height) this.y = 0;
if (this.y < 0) this.y = height;
}
draw(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI, false);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.fill();
ctx.globalAlpha = 1.0;
}
}
// === Initialize Particles ===
const particles = [];
const numParticles = 100;
for (let i = 0; i < numParticles; i++) {
particles.push(new Particle());
}
// === Animation Loop ===
function animate() {
// Draw a semi-transparent rectangle to create trail effect
ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'; // Adjust the alpha for trail length
ctx.fillRect(0, 0, width, height);
particles.forEach(p => {
p.update();
p.draw(ctx);
});
requestAnimationFrame(animate);
}
// Start the animation
animate();
// === Ambient Sound Setup ===
function createWhiteNoise(context) {
const bufferSize = 2 * context.sampleRate;
const buffer = context.createBuffer(1, bufferSize, context.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
const whiteNoise = context.createBufferSource();
whiteNoise.buffer = buffer;
whiteNoise.loop = true;
whiteNoise.start(0);
return whiteNoise;
}
function startAmbientSound() {
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
// Create white noise
const whiteNoise = createWhiteNoise(audioCtx);
// Create gain node for volume control
const gainNode = audioCtx.createGain();
gainNode.gain.value = 0.1; // Adjust volume here (0.0 to 1.0)
whiteNoise.connect(gainNode).connect(audioCtx.destination);
return () => {
whiteNoise.stop();
audioCtx.close();
};
}
// Start the ambient sound on user interaction to comply with browser policies
let stopSound = null;
function initSound() {
stopSound = startAmbientSound();
// Remove the click listener after starting
window.removeEventListener('click', initSound);
window.removeEventListener('keydown', initSound);
}
// Add event listeners for user interaction
window.addEventListener('click', initSound);
window.addEventListener('keydown', initSound);
// Optional: Display a message to prompt user interaction
const message = document.createElement('div');
message.style.position = 'absolute';
message.style.top = '50%';
message.style.left = '50%';
message.style.transform = 'translate(-50%, -50%)';
message.style.color = '#fff';
message.style.fontFamily = 'Arial, sans-serif';
message.style.textAlign = 'center';
message.style.pointerEvents = 'none';
message.style.userSelect = 'none';
message.textContent = 'Click or press any key to start ambient sounds';
document.body.appendChild(message);
// Remove the message once the sound starts
function removeMessage() {
if (stopSound) {
document.body.removeChild(message);
window.removeEventListener('click', initSound);
window.removeEventListener('keydown', initSound);
}
}
window.addEventListener('click', removeMessage);
window.addEventListener('keydown', removeMessage);
</script>
</body>
</html>
Explanation of Key Components:
-
Canvas and Particles:
- The
<canvas> element fills the entire browser window.
- The
Particle class defines individual particles with random positions, velocities, sizes, and colors.
- An animation loop (
animate function) updates and draws each particle on every frame. A semi-transparent black rectangle is drawn over the entire canvas each frame to create the trailing effect.
-
Ambient Sound:
- Utilizes the Web Audio API to generate white noise, which is looping and played at a low volume.
- Due to browser autoplay policies, the sound starts only after a user interaction (click or keypress). A prompt message guides the user to initiate the sound.
-
User Interaction Handling:
- The ambient sound setup is triggered by the first user interaction (click or keypress) to comply with modern browser restrictions on autoplaying audio.
- Once the sound starts, the prompt message is removed.
Customization:
- Number of Particles: You can adjust the
numParticles variable to increase or decrease the number of particles on the screen.
- Particle Colors: The particles use random hues with a fixed saturation and lightness. You can modify the
hsl values in the Particle class to change the color scheme.
- Trail Effect: Modify the
rgba value in ctx.fillStyle within the animate function to change how long the trails persist. Lower alpha values result in longer trails.
- Ambient Sound Volume: Adjust the
gainNode.gain.value in the startAmbientSound function to increase or decrease the volume of the ambient sound.
Feel free to customize the visual and auditory elements to better suit your personal relaxation preferences. Enjoy a peaceful and restful sleep!