我最近访问了该网站,其中包含一些缓动功能:http://gizma.com/easing/
并试图从中实现一个quadratic easing in/out
到我的脚本中,但是我的精灵似乎很快就消失了。我不确定我的逻辑哪里出了问题,需要一些帮助来理解我的错误。
我的缓动函数如下所示:
//t = time, b = startvalue, c = change in value
function ease(t, b, c, duration) {
t /= duration/2; //duration is in milliseconds
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
我的动画动画代码是从
mousedown
侦听器触发的:function animate(e){
clearTimeout(timer);
var duration = 2000; //2 seconds
var startX = camera.x;
var startY = camera.y;
var targetX = e.offsetX - element.width/2 + camera.x; //world space
var targetY = e.offsetY - element.height/2 + camera.y; //world space
var vectorX = targetX - startX / duration;
var vectorY = targetY - startY / duration;
var startTime = Date.now();
function update(){
var t = Date.now() - startTime; //time elapsed so far
var cX = vectorX * t; //change in X
var cY = vectorY * t; //change in Y
var amountX = ease(t,startX,cX,duration); // see function above
var amountY = ease(t,startY,cY,duration);
var difX = startX - amountX; //get the difference
var difY = startY - amountY;
camera.x += difX;
camera.y += difY;
if (t >= duration){
clearTimeout(timer);
} else {
timer = setTimeout(update,0);
}
}
update();
}
是什么原因导致动画如此快速,如此远地发展?
编辑:添加了,一个小提琴包围它可以帮助:http://jsfiddle.net/a86m33nj/
最佳答案
https://jsfiddle.net/pcconsolidated/xesnom2t/
您的问题仅仅是使问题复杂化。二次缓动函数只想知道开始坐标,将其移动多远,相对于开始时间的当前时间以及总持续时间。同样,二次方的输出是新坐标,而不是对象移动的距离,因此只需将坐标替换为四舍五入到最接近数字的函数值即可。
var element = document.getElementById('background');
var output = document.getElementById('output');
var camera=document.getElementById("camera");
var timer;
var targetX=0;
var targetY=0;
document.addEventListener('click', animate,true);
var duration = 2000; //2 seconds
var startX = 0;
var startY = 0;
var startTime =0;
function animate(e){
targetX = e.clientX ;
targetY = e.clientY ;
clearTimeout(timer);
startX = parseInt(camera.style.left.split("p")[0]);
startY = parseInt(camera.style.top.split("p")[0]);
startTime = Date.now();
updateLoc();
}
function updateLoc(){
var t = (Date.now() - startTime);
var cX = targetX-startX; //change in X
var cY = targetY-startY; //change in Y
var amountX = ease(t,startX,cX,duration);
var amountY = ease(t,startY,cY,duration);
newX=Math.floor(amountX);
newY=Math.floor(amountY);
camera.style.left = Math.floor(newX)+"px";
camera.style.top = Math.floor(newY)+"px";
output.innerHTML+=newX+","+newY+"___";
if (Date.now() - startTime >= duration){
clearTimeout(timer);
} else {
timer = setTimeout(updateLoc,0);
}
}
//t = time, b = startvalue, c = change in value
function ease(t, b, c,duration) {
t /= duration/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
</script>
<canvas id="background" width="500" height="500">
</canvas><br/>
<div id="output"></div><div id="camera" style="background-color:green;top:250px;left:150px;position:absolute;height:30px;width:30px;"></div>
<script type="text/javascript">
相当虚张声势,我的补偿在某处是错误的,但是生病后晚餐后继续修补,看看我能不能得到。这是我的代码,希望它对您有用。