Why are slow jQuery animations choppy?

2020-07-04 07:49发布

问题:

I'm having a hard time googling this issue because most of the things I can find are about animations that are supposed to be fast but are acting slow. My question is regarding an animation that I want to have a long duration but still be smooth.

I've created this jsfiddle to demonstrate the issue: http://jsfiddle.net/93Bqx/

I'm trying to make an element slowly move to another position over time. But the animation is very choppy.

Basically, it boils down to something like this:

$elem.animate({
        left: x,
        top: y
}, someLargeNumber);

I'm wondering if the problem is that the animation is so slow that each step is less than a pixel and so it is rounding them to either 0 or 1 making it appear to drop frames and then move all at once. But I don't know how I would check or fix this.

Is there a better way to be doing slow animations so they're smooth? I had a similar one created with CSS3 and translate(x,y) that was smooth but unfortunately I need more flexibility than I think I can get with CSS.

回答1:

It's not much smoother even using a CSS transition.

I added the Transit jQuery plugin to test a CSS transition instead, and it looks almost the same.

Your code with minor fixes: http://jsfiddle.net/thirtydot/93Bqx/5/

Same code but with Transit added: http://jsfiddle.net/thirtydot/93Bqx/6/.

I think this is a limitation of the fact that (most?) browsers don't do subpixel rendering. As you mentioned, the x and y of the element is rounded after every step of the animation, and it's this rounding that causes the unsightly "jiggling" effect.

The CSS transition version does look noticeably better for less pathological test cases. Read this for more information: http://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/



回答2:

I guess it's the inevitable bargain with doing animation programmatically. Maybe try a framework specialized in animation like:

http://www.greensock.com/gsap-js/

but adapting the animation to CSS would be best.



回答3:

I think it has something to do with how often you move an element. For example, if you move the object once every second, it will seem choppy. Try decreasing the amount of time between each move as well as decreasing the distance between each move. See http://jsfiddle.net/2K9xP/ for an example.

So we have...

var duration = Math.round(10 * distance);

instead of...

var duration = Math.round(1000 * distance);