I am doing a small JavaScript animation hoping that the little div can move along a sine wave, and for the moment the horizontal path works fine (just straight line). I am almost sure that my math formula for the Y axis is wrong. I have tried to correct it with some examples I found, but none of them worked for me. In all the possibilities I tried, the Y axis is ignored and the little box just moves in straight line horizontally.
How can I fix this, so the movement goes along a sine wave? I know that it’s possible to do it easier with jQuery or using html 5, but I just got wondering what is wrong in my original code… I would prefer to fix this if possible.
function animate() {
xnow = item.style.left;
item.style.left = parseInt(xnow)+1+'px';
ynow = item.style.top;
item.style.top = ynow + (Math.sin((2*Math.PI*xnow)/document.width))*document.heigth;
setTimeout(animate,20);
}
The complete code here:
JSFiddle
I see several problems with your code:
xnowcontains a string in this format:###pxYou cannot multiply it, so useparseInt()in yourMath.sin()call.ynow, it needsparseInt().pxwhen you update coordinates of the div-element.2*Math.PIwithxnow(which contains only integer numbers), thesin()function will always return0. So you won’t get a sine-like movement. You need to dividexnowby the number of x-steps you want to use to do a complete sine-like movementMath.sin()returns a value between -1 and +1, so you need to multiply it by an amplitude to see a (more clear) effect.To keep it as much as you designed it, it would become something like this (takes 50 x-movement steps to do a complete sine and uses an amplitude of 10 pixels):
As mentioned: it is much better to use some global variables containing the values (instead of using
parseInt()all the time)See my updated JSFiddle example.