开发者

jQuery smooth mouse tracking

I have my object tracking the mouse using the onmousemove event. But I wou开发者_开发问答ld like to make it smooth. I'm sure this can't be difficult in jQuery but I'm not finding any really good resources.

One idea I had was to simply use the animate function and calculating the offsets that I want to move to. Then if the mouse moves again before the animation is complete, I would use the stop function to stop the animation. I would recalculate my destination and away I go again. This seems a little hack-ish and I also imagine that it will be a little jerky. I'm sure there has to be a better way. Any Ideas?

EDIT

Sorry I didn't make my problem very clear. I have the object tracking the mouse in real time, so that it moves exactly the same as my mouse. The problem is that I want it to be smooth and lag behind with acceleration effects like Andy Lin mentioned below. I'm just a little lost how to actually implement this.


I am afraid, that there is no better way, than animate. If you add a smoothing function, then you would simply do the same thing that animate does. Be sure, not to queue your animations or they will look weird. I got nice results with this:

var obj = $('<div style="width:50px;height:50px;background:red;position:absolute"></div>');

obj.appendTo(document.body);

$(document).bind('mousemove',function(ev){
 obj.animate({top:ev.pageY,left:ev.pageX},{queue:false,duration:200,easing:'linear'})});


when you are using onmousemove, you do not need to have the object change its behavior with every invocation.

e.g. you can add a timer to say that within period of time, the object will not response to mousemove and will follow its original path, and upon timeout or mouse move stop, move according to the destination.

also, you can simulate an acceleration and slow down effect with animation settings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜