Небольшой примерчик
<div id="moved" style="position: absolute;width:30px;height: 30px;background: red;"></div>
<br>
<input type="button" onclick="but1()" value="кнопка 1"> <br>
<input type="button" onclick="but2()" value="кнопка 2">
<script type="text/javascript">
var RequestAnimationFrame = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
function but1 (){
var element = document.getElementById("moved");
animateMove( element , 800 , 100 , 1500 , function () {
animateMove( element , -750 , 10 , 200 ,function (){
animateMove( element , 150 , -60 , 1000 ,function (){
element.style.background = ("#" + ( Math.random() * (999-100)+100 )).substr(0,4) ;
element.style.top = "30px";
element.style.left = "100px";
})
})
})
}
function but2 (){
var element = document.getElementById("moved");
var animation = animateMove( element , 100 , 0 , 10000 );
element.onclick = function () {
animation.time = 1;
animation.onFinish = null;
};
animation.onFinish = function (){
animateMove( element , -100 , 50 , 5000 );
element.onclick = null;
};
}
function animateMove ( element , x , y , time ,callBack){
var j = animateMove;
j.time = time || 1000;
j.x = x;
j.y = y;
j.statX = element.offsetLeft;
j.startY = element.offsetTop;
j.onFinish = callBack;
j.animate = function (){
if ( j.startTime == undefined ){ j.startTime = new Date().getTime() }
var Time = new Date().getTime();
var EA = ( (Time - j.startTime) || 1 )/j.time;
if ( EA < 1) {
element.style.left = j.statX + (j.x * EA) + "px";
element.style.top = j.startY + (j.y * EA) + "px";
RequestAnimationFrame(j.animate );
}else{
delete j.startTime;
j.onFinish? j.onFinish():0;
}
};
j.animate();
return j;
}
</script>