Music wave pattern

by Ben Gillbanks

HTML

<canvas id="plotCanvas" width="800" height="400"></canvas>

CSS

body {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			height: 100vh;
			background-color: #f5f5f5;
		}
		canvas {
			border: 1px solid black;
		}

JavaScript

// Canvas setup
		const canvas = document.getElementById('plotCanvas');
		const ctx = canvas.getContext('2d');
		const width = canvas.width;
		const height = canvas.height;
		let time = 0;

		// Function to generate the music pattern
		function generateMusicPattern1(t) {
			const sine = Math.sin(t);
			//const noise = (Math.random() - 0.5); // Add some randomness
            const noise = 1;
			const lfo = Math.cos(0.6 * t); // LFO for modulation
			return (sine + noise) * lfo;
		}
        
        function generateMusicPattern(t) {
    const amplitude = 0.5 + Math.random() * 0.2; // Randomly vary amplitude between 0.8 and 1.0
    const sine = amplitude * Math.sin(t);
    const noise = 1; // Add some randomness
    const lfo = Math.cos(0.6 * t); // LFO for modulation
    const lfo2 = Math.sin( 0.3 * t );
    return (sine + noise) * lfo * lfo2;
}


		// Draw loop to plot the values
		function draw() {
			ctx.clearRect(0, 0, width, height); // Clear canvas

			ctx.beginPath();
			ctx.moveTo(0, height / 2); // Start at the center of the canvas

			for (let x = 0; x < width; x++) {
				const t = time + x * 0.02; // Scale time for better visualization
				const yValue = generateMusicPattern(t);
				const y = height / 2 - yValue * 100; // Scale and center on the canvas

				ctx.lineTo(x, y);
			}

			ctx.strokeStyle = 'blue';
			ctx.lineWidth = 2;
			ctx.stroke();

			time += 0.05; // Increment time for animation

			requestAnimationFrame(draw); // Continuously update the plot
		}

		// Start drawing
		draw();