JavaScript: Achieving precise animation end values?
Posted
by bobthabuilda
on Stack Overflow
See other posts from Stack Overflow
or by bobthabuilda
Published on 2010-04-19T16:59:57Z
Indexed on
2010/04/19
17:03 UTC
Read the original article
Hit count: 333
I'm currently trying to write my own JavaScript library. I'm in the middle of writing an animation callback, but I'm having trouble getting precise end values, especially when animation duration times are smaller.
Right now, I'm only targeting positional animation (left, top, right, bottom). When my animations complete, they end up having an error margin of 5px~ on faster animations, and 0.5px~ on animations 1000+ ms or greater. Here's the bulk of the callback, with notes following.
var current = parseFloat( this[0].style[prop] || 0 )
// If our target value is greater than the current
, gt = !!( value > current )
, delta = ( Math.abs(current - value) / (duration / 13) ) * (gt ? 1 : -1)
, elem = this[0]
, anim = setInterval( function(){
elem.style[prop] = ( current + delta ) + 'px';
current = parseFloat( elem.style[prop] );
if ( gt && current >= value || !gt && current <= value ) clearInterval( anim );
}, 13 );
this[0]
and elem
both reference the target DOM element.
prop
references the property to animate, left
, top
, bottom
, right
, etc.
current
is the current value of the DOM element's property.
value
is the desired value to animate to.
duration
is the specified duration (in ms) that the animation should last.
13
is the setInterval
delay (which should roughly be the absolute minimal for all browsers).
gt
is a var
that is true
if value
exceeds the initial current
, else it is false
.
How can I resolve the error margin?
© Stack Overflow or respective owner