首先用一个例子来演示这个效果:
鼠标可以拖曳和投掷小球
拖曳功能比较简单,主要难点在如何计算投掷时的速度。
用一张图来说明:
物体在动画行进一帧的间隔内从a点被鼠标拖动到了b点,很显然在这个过程中物体的运动速度为:
vx = b.x - a.x;
vy = b.y - a.y;
只要在鼠标按下时记录小球的位置,然后在拖动时不断计算小球当前位置与旧位置的距离,就能得到小球的速度:
canvas.addEventListener(‘mousedown‘,function() { oldX = ball.x; oldY = ball.y; canvas.addEventListener(‘mousemove‘,onMouseMove,false); canvas.addEventListener(‘mouseup‘,onMouseUp,false); },false); function onMouseMove() { ball.x = mouse.x; ball.y = mouse.y; } function onMouseUp() { canvas.removeEventListener(‘mousemove‘,onMouseMove,false); canvas.removeEventListener(‘mouseup‘,onMouseUp,false); } function trackVelocity() { vx = ball.x - oldX; vy = ball.y - oldY; oldX = ball.x; oldY = ball.y; } (function() { window.requestAnimFrame(arguments.callee,canvas); ctx.clearRect(0,0,canvas.width,canvas.height); trackVelocity(); ball.draw(ctx); })();
原文:http://www.cnblogs.com/undefined000/p/5218539.html