如何将div动画的方向更改为单击的方向,然后继续沿该方向动画?

时间:2017-05-29 09:02:58

标签: javascript html animation

我想为已经处于动画状态的div设置朝向点击方向的动画,然后动画应该继续沿着该特定方向。

以下是我所做的事情的链接。

 public function addUserInformation(Request $request){
            $this->validate($request, [
                'name' => 'required|string|min:5',
                'email' => 'required|string|email|unique:users,email',
                'designation' => 'required|exists:designation,id',
                'password'     => 'required|min:6',
                'confirm_password' => 'required|same:password',
                'userimage' => 'required|image',
            ]);
            $selectedID = $request->input('designation');
}
var $follower = $("#follower"),
    mouseX = 0, 
    mouseY = 0;

$(document).click(function(e){
   mouseX = e.pageX;
   mouseY = e.pageY; 
   $follower.stop().animate({left : mouseX, top: mouseY});
});
#follower{
  position : absolute;
  background-color : red;
  color : white;
  padding : 10px;
}

1 个答案:

答案 0 :(得分:0)

您需要使用window.requestAnimationFrame

如果您愿意,也可以匹配speed。但这是另一个层次; - )

var $follower = $("#follower"),
    mouseX = 0, 
    mouseY = 0,
    vector = { x:0, y:0 },
    isFirst = true,
    speed = 0;

$(document).click(function(e){
   mouseX = e.pageX;
   mouseY = e.pageY;
   vector = {
   	x: $follower.offset().left - mouseX,
   	y: $follower.offset().top - mouseY
   }
   speed = Math.sqrt( Math.pow( vector.x, 2 ) + Math.pow( vector.y, 2)) * 0.0001;
   $follower.stop().animate({left : mouseX, top: mouseY}, init );
});

function init() 
{ 
  if (isFirst) { render(); }
  isFirst = false;
}

function render()
{
  var left = $follower.position().left -  vector.x * speed;
  var top = $follower.position().top -  vector.y * speed;
  //  Never leave the page
  if ( left < 0 && vector.x > 0 ) { left = $(window).width() }
  if ( left > $(window).width() && vector.x < 0 )  { left = 0 }
  if ( top < 0 && vector.y > 0 ) { top = $(window).height() }
  if ( top > $(window).height() && vector.y < 0 )  { top = 0 }

  $follower.css({ left: left, top: top })
  window.requestAnimationFrame( render )
}
#follower{
  position : absolute;
  background-color : red;
  color : white;
  padding : 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="follower"></div>