如何使用Javascript在滚动事件上创建“简单谐波振荡”

时间:2017-09-12 11:06:10

标签: javascript jquery physics

目前我在页面上有一个元素。我希望该对象左右振荡,类似于下面示例中给出的对象。但是,我想用浏览器窗口滚动事件绑定振荡。

https://www.khanacademy.org/computer-programming/simple-harmonic-motion/4920589909229568

我尝试了这个,但它并不顺畅和准确:

Javascript

    let butterfly_y_position_log = []; 
    let scroll_times = 0;
    let scroll_direction;
    $(window).scroll(function(){
      let butterfly_y_position = $('.floating-butterfly').offset().top;
      let butterfly_x_position;
      butterfly_y_position_log.push(butterfly_y_position);
      if (butterfly_y_position_log.length > 2){
        butterfly_y_position_log = butterfly_y_position_log.slice(1, 4);
      }

      if (butterfly_y_position_log[0] < butterfly_y_position_log[1] || butterfly_y_position_log[1] == undefined){
        scroll_direction = 'down';
        scroll_times++;
        butterfly_x_position =  ($(window).width() / 2) + (100 * Math.sin(2* Math.PI + scroll_times));
      } else {
        scroll_direction = 'up';
        scroll_times--;
        butterfly_x_position =  ($(window).width() / 2) + (100 * Math.cos(2* Math.PI + scroll_times));
      }
      console.log(scroll_times);
      console.log(butterfly_x_position);
      $('.floating-butterfly').css({left:butterfly_x_position});
    });

HTML

<img src="..." class="floating-butterfly">

CSS

.floating-butterfly {
  position: fixed;
  top: 40px;
  z-index: 2;
}

Y位置将保持固定,只有X位置会在滚动时改变。

enter image description here

0 个答案:

没有答案