javascripthtmltranslatemomentum

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


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.


Solution

  • One method is using animation-timing-function:, which I believe currently requires vendor prefixes. You have a choice of using ease-in, ease-out, ease-in-out, or cubic-bezier. The latter uses the visualization of a function in 2D space; it's easier to configure that one using a generator. My personal favorite is Ceaser.