2016-07-19 106 views
1

我有一个图像在父元素内部旋转和反射。我让它工作得很好,期待旋转看起来有点棘手。开始的几秒钟很平稳,然后开始晃动一下。平滑抖动的jquery动画

我该如何解决这个问题?

$.fn.bounce = function(options) { 

    var settings = $.extend({ 
     speed: 10 
    }, options); 

    return $(this).each(function() { 

     var $this = $(this), 
      $parent = $this.parent(), 
      height = $parent.height(), 
      width = $parent.width(), 
      top = Math.floor(Math.random() * (height/2)) + height/4, 
      left = Math.floor(Math.random() * (width/2)) + width/4, 
      vectorX = settings.speed * (Math.random() > 0.5 ? 1 : -1), 
      vectorY = settings.speed * (Math.random() > 0.5 ? 1 : -1); 

     // place initialy in a random location 
     $this.css({ 
      'top': top, 
      'left': left 
     }).data('vector', { 
      'x': vectorX, 
      'y': vectorY 
     }); 

     var move = function($e) { 

      var offset = $e.offset(), 
       width = $e.width(), 
       height = $e.height(), 
       vector = $e.data('vector'), 
       $parent = $e.parent(); 

      if (offset.left <= 0 && vector.x < 0) { 
       vector.x = -1 * vector.x; 
      } 
      if ((offset.left + width) >= $parent.width()) { 
       vector.x = -1 * vector.x; 
      } 
      if (offset.top <= 0 && vector.y < 0) { 
       vector.y = -1 * vector.y; 
      } 
      if ((offset.top + height) >= $parent.height()) { 
       vector.y = -1 * vector.y; 
      } 

      $e.css({ 
       'top': offset.top + vector.y + 'px', 
       'left': offset.left + vector.x + 'px' 
      }).data('vector', { 
       'x': vector.x, 
       'y': vector.y 
      }); 

      setTimeout(function() { 
       move($e); 
      }, 50); 

     }; 

     move($this); 
    }); 

}; 

$(function() { 
    $('#wrapper li').bounce({ 
     'speed': 7 
    }); 
}); 

$(function() { 
    var $elie = $("img"); 
    rotate(0); 
    function rotate(degree) {   
     $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'}); 
     $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});      
     timer = setTimeout(function() { 
      rotate(--degree); 
     },30); 
    } 
}); 

JS FIDDLE

+0

#nsfw - 该图像是可怕的 –

+0

对我来说,这是在开始更加生涩,然后稳定下来的干岬 –

+0

解决您的动画,最好的办法是不使用jQuery 。 – ndugger

回答

1

在你的方法抖动现象是从50超时值的简单优化是只删除该时间间隔和调整矢量的变化,以保持大致相同的速度。

setTimeout(function() { 
    move($e); 
}, 0); 

vectorX = settings.speed * (Math.random() > 0.5 ? 0.1 : -0.1), 
vectorY = settings.speed * (Math.random() > 0.5 ? 0.1 : -0.1); 

http://jsfiddle.net/k3uvb5c0/6/