Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and Canvas - Animating a Sine wave

So, I have the following code to animate something upwards... it's very basic...

SetInterval(function() {
   particlesY -= 1;
}, 10);

Then a loop as such:

ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawRect(50, particlesY, 32, 32);

This works fine, but I want a bit of X-Axis variation - I can use Math.random() to get a random direction, but the result is very jerky and pretty much laughable.

I figured that a sine wave would give me a nice smooth X-Axis change.

Any ideas? :(

like image 282
Barrie Reader Avatar asked May 03 '26 06:05

Barrie Reader


1 Answers

A sine wave should be fairly straightforward:

ctx.drawRect( Math.sin(particlesY) * 100, particlesY, 32, 32);
like image 72
bharling Avatar answered May 05 '26 18:05

bharling