书籍名称:HTML5-Animation-with-JavaScript
书籍源码:https://github.com/lamberta/html5-animation1
1.释放
现在假设我们写一个动画,将它运动到指定的地方,先设置一个速度,运用三角函数,我们计算x的速度,计算y的速度,判断距离。到达终点时停止。
这种方法在有些情况适用,但某些情况下,我们想让物体运动的自然一些。
在一些运动,我们知道目标,且一开始速度很快,后面逐渐变慢。也就是说,它的速度和距离是成正比的。看下图。
01-easing-1.html
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Easing 1</title> <link rel="stylesheet" href="../include/style.css"> </head> <body> <header> Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a> </header> <canvas id="canvas" width="400" height="400"></canvas> <script src="../include/utils.js"></script> <script src="./classes/ball.js"></script> <script> window.onload = function () { var canvas = document.getElementById(‘canvas‘), context = canvas.getContext(‘2d‘), ball = new Ball(), easing = 0.05, targetX = canvas.width / 2, targetY = canvas.height / 2; (function drawFrame () { window.requestAnimationFrame(drawFrame, canvas); context.clearRect(0, 0, canvas.width, canvas.height); var vx = (targetX - ball.x) * easing, vy = (targetY - ball.y) * easing; ball.x += vx; ball.y += vy; ball.draw(context); }()); }; </script> </body> </html>
时间: 2024-10-11 21:08:52