如何获得像模数模式的窦(How to get a sinus like modulo pattern)

编程入门 行业动态 更新时间:2024-10-24 16:29:25
如何获得像模数模式的窦(How to get a sinus like modulo pattern)

我正在尝试使用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 %.

更多推荐

本文发布于:2023-08-03 12:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391963.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   模数   模式   pattern   modulo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!