Scrolling a jQuery animation backwards and forwards

99封情书 提交于 2019-12-05 00:17:31

问题


I am making a futsal (indoor soccer) coaching application which allows a coach to add players on the screen, set their movement direction (by drawing arrows using HTML5 canvas), and then press 'play' to move all players on the screen. A player is made up of a div with a background image of a player.

Animation is being done by using jquery .animate() function.

All I do is change the player div's left and top css position attributes.

I would like to do two things and unsure on how that can be done:

  1. I want to create a jQuery slider and move it incremently as the animation takes place. I am guessing I would do this by calculating the total length of an animation before starting it?

  2. I would like to move the jQuery slider above backwards and forth - to reverse the animataion and pause it when required. is that possible at all given that we are moving divs for animation, and not doing a frame-by-frame sequence animation.


回答1:


Before the animation starts, how about saving the starting position?

startpostion = $(playerdiv).position(); //Or offset, I keep forgetting which
$(playerdiv).data("startTop",startposition.top);
$(playerdiv).data("startLeft",startposition.left);

Later you can retrieve it using

left = $(playerdiv).data("startTop")

etc.

You can allways provide a callback to animations using the step option, this way you can update your slider accordingly.

$(playerdiv).animate({ 
    top : targetTop,
    left : targetLeft, 
    step, function(){ magic happens here
})



回答2:


I would do it this way:

  1. If the user clicks "Play", start animating the divs from their current position to their destination. You can easily calculate remaining time and divs position depending on the slider's position:

    • startingDivTop = initialDivTop + (finalDivTop - initialDivTop) * sliderPosition;
    • startingDivLeft = initialDivLeft + (finalDivLeft - initialDivLeft) * sliderPosition;
    • startingTime = totalDuration * sliderPosition;

    (or something like that, where sliderPosition is something between 0 and 1)

  2. If the user clicks again over the slider, call the .stop() method on all divs: that way they will stop animating and you'll be able to set them statically: calculate the position the divs should be at and move them statically to that point.

  3. If the user "drops" the slider and "Play" is still activated, then animation should continue forwards from the point the slider was dropped.

It sounds like a nice project you're working on :)



来源:https://stackoverflow.com/questions/664867/scrolling-a-jquery-animation-backwards-and-forwards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!