I've made a simple grabbing demo page. It doesn't have any easing/acceleration. I would like to do the same easing/acceleration as on kulesh.info (Flash website) using JavaScript. How can I do that?
Any examples of smooth grabbing (scrolling, dragging) in JavaScript would be helpful as well as a language agnostic algorithm.
You can get the flash look by using an easing equation sometimes referred to as zeno's paradox.
position += (destination - position) / damping
I modified your jsFiddle to make use of it: Have a look
If you'd like me to give a more detailed description of zeno's paradox, let me know and I'll post one here with an image or two.
I think this is the best you can get with jQuery: [Demo]
jQuery.fx.interval = 1; // since v1.4.3
var photos = $(".photos");
var scrollLeft = photos[0].scrollLeft;
var $el = $(photos[0]);
var lastTime = +new Date();
$(window).mousemove(function(event){
var now = +new Date();
var elapsed = now - lastTime;
if (dragging && elapsed > 10) {
scrollLeft += x - event.clientX;
$el.stop().animate({scrollLeft: scrollLeft}, 300, "easeOutCubic");
x = event.clientX;
lastTime = +new Date();
}
});
$(window).mouseup(function(event){
dragging = false;
$el.stop().animate({scrollLeft: scrollLeft}, 500, "easeOutCubic");
});
Note, all the possible (slight) sluggishness can't be corrected at the moment, because it's related to image rendering performance of modern browsers. Test - simple linear animation, no events, no jQuery
Try replacing this line:
photos[0].scrollLeft += x - event.clientX;
with this (Updated demo):
photos.animate({ scrollLeft : '+=' + (x - event.clientX) }, 12, 'easeOutCirc');
Note that I clicked on jQuery UI to include the easing options. Also, it is very jumpy in the jFiddle (using Firefox) demo, but it doesn't do that at all when I test it on my desktop or if I look at that demo in Chrome. Ideally using the easing function without using jQuery animate would be best. But this should give you an idea.
var dragging = false;
var x, startX, startTime, stopTime;
var photos = $(".photos");
photos.mousedown(function(event){
dragging = true;
startX = x = event.clientX;
startTime = new Date();
event.preventDefault();
});
$(window).mousemove(function(event){
if (dragging) {
photos[0].scrollLeft += x - event.clientX;
stopTime = new Date();
x = event.clientX;
}
});
$(window).mouseup(function(event){
dragging = false;
var left = photos[0].scrollLeft;
var dx = (startX - event.clientX);
var time = stopTime - startTime;
var speed =time/dx;
photos.animate({ scrollLeft : (left + dx*time/500), easing :'swing' }, 100/time*1000);
});
来源:https://stackoverflow.com/questions/4234489/smooth-grabbing