我正在尝试使用javascript在我的网站上获得一个漂亮的上下动画,但我需要一个这样的序列:
0 1 2 3 4 3 2 1 0 1 2 3 4 ...
但是我倾向于用于重复操作的模块只给了我:
0 1 2 3 4 0 1 2 3 4 0 1 2 ...
如何获得圆形图案,例如从i++变量。
我试过应用一个正弦波。
I'm trying to get a nice up and down animation going on my website using javascript, but I need a sequence like this:
0 1 2 3 4 3 2 1 0 1 2 3 4 ...
But module which I tend to use for repetitive actions only gives me:
0 1 2 3 4 0 1 2 3 4 0 1 2 ...
How can I get a circular pattern, for example from a i++ variable.
I tried applying a sinus wave for example.
最满意答案
你似乎想要的是三角波。 试试这个:
var period = 8, amplitude = 4; for (var i = 0; i < 50; i++) { console.log( amplitude * Math.abs( 2*(i/period - Math.floor(i/period + 1/2)) ) ) }这是一个使用模数运算符的版本:
var period = 8, amplitude = 4; for (var i = 0; i < 50; i++) { console.log( (2 * amplitude/period) * ( Math.abs(((i + period/2) % period) - period/2) ) ) }这两个工作的原理是你可以通过获取锯齿波的绝对值来创建三角波。 在第一个中,我们使用Math.floor创建锯齿波,在第二个中我们使用% 。
What you seem to want is a triangle wave. Try this out:
var period = 8, amplitude = 4; for (var i = 0; i < 50; i++) { console.log( amplitude * Math.abs( 2*(i/period - Math.floor(i/period + 1/2)) ) ) }Here's a version which uses the modulus operator:
var period = 8, amplitude = 4; for (var i = 0; i < 50; i++) { console.log( (2 * amplitude/period) * ( Math.abs(((i + period/2) % period) - period/2) ) ) }Both of these work on the principle that you can create a triangle wave by taking the absolute value of a sawtooth wave. In the first we use Math.floor to create a sawtooth wave and in the second we use %.
更多推荐
发布评论