Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sangelxyz/97752321878bf71ac0cf0cfa065c1464 to your computer and use it in GitHub Desktop.
Save sangelxyz/97752321878bf71ac0cf0cfa065c1464 to your computer and use it in GitHub Desktop.
javascript sinewave animation on canvas
document.addEventListener('DOMContentLoaded', function() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions
canvas.width = 800;
canvas.height = 400;
let wave = {
y: canvas.height / 2,
length: 0.009,
amplitude: canvas.height / 2,
frequency: 0.019
};
let increment = wave.frequency;
function animate() {
requestAnimationFrame(animate); // Tells the browser that you wish to perform an animation
ctx.fillStyle = 'rgba(255, 255, 255, 0.1)'; // Trail effect
ctx.fillRect(0, 0, canvas.width, canvas.height); // Redraws the background
ctx.beginPath(); // Starts a new path
ctx.moveTo(0, canvas.height / 2); // Move to the middle of the canvas
for (let i = 0; i < canvas.width; i++) {
ctx.lineTo(i, wave.y + Math.sin(i * wave.length + increment) * wave.amplitude * Math.sin(increment));
}
ctx.strokeStyle = 'blue'; // Color of the sine wave
ctx.stroke(); // Renders the path
increment += wave.frequency;
}
animate(); // Start the animation
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment