How can I add momentum / inertia to a drag using CSS transform?

BBog picture BBog · Aug 20, 2012 · Viewed 8.3k times · Source

I am trying to add a momentum / inertia effect to a zoomed image drag (like in this example or just like iOs does it) and I'm having a tough time with it.

I've been struggling with this for a while and found some helpful resources (like this one) but most of the solutions involve jQuery and I would prefer to stick to plain javascript, no frameworks involved.

I'm working on a HTML5 / CSS3 zoom image code, with all the standard features: double-tap zoom, pinch zooming, dragging, panning, etc. and everything is done using CSS3's transform translation, combined with the scaling. Ex.

transform: translate(100px, 100px);
transition: 100ms;

I looked at how others are doing it and it involves consecutive animations of the left/right properties, with decreasing duration / distance, to create a sort of ease-in effect.

I tried to recreate it using translations, using a sort of recursive function (you can see a fiddle here (works with webkit browsers), please ignore the coding style, it was not meant to be best practice, just a demo). In this case, the animation is not fluid it all, the consecutive translations do not connect.

I have a somewhat basic understanding of the principle and I did take a look at some algorithms available online but I just can't figure out how can I achieve this using css translations.

The first part of the dragging, done on mousemove/touchmove moves the image with the cursor/finger but the continuing translation after the end is not... continuous, it's like a separate animation after the first one and doesn't resemble a natural momentum / inertia effect.

Answer

BBog picture BBog · Aug 21, 2012

I managed to find something helpful in the end, it is still a work in progress but the results look promising.

The starting point was this post made by Aryia Hidayat and in particular his Kinetic Scroll, as well as a post made by Joe Hewitt. Also, this older version of his code seemed easier to understand and grasp the basic concept, even though the most recent should be better.

Basically, instead of connecting various translations with a non-null duration and synchronize their timing and acceleration, this method uses a large number of 0-duration translations, called very often.