缓动是指物体滑动到目标点就停止。
实现缓动策略:
- 为运动确定一个比例系数,这是一个小于1且大于0的小数
let easing = 0.05;
- 确定目标点,假设为canvas中心点位置
let targetX = canvas.width / 2; let targetY = canvas.height / 2;
- 计算出物体(小球 ball )与目标点(canvas中心点位置)的距离
let dx = targetX - ball.x; let dy = targetY - ball.y;
- 计算速度,速度=距离 * 比例系数
let vx = dx * easing; let vy = dy * easing;
- 用当前位置加上速度来计算新的位置
ball.x += vx; ball.y += vy;
- 重复第3步到第5步,直到物体到达目标点
代码实现如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no,width=device-width">
<title></title>
<style>
*{margin: 0;padding: 0}
body {
background-color: #eee
}
canvas {
background-color: #fff
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400">
Your browser does not support HTML5 Canvas.
</canvas>
<script>
(function(){
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
canvasApp();
}
function canvasSupport(e){
return !!e.getContext;
}
function canvasApp(){
let canvas = document.getElementById("canvas");
if(!canvasSupport(canvas)){
return ;
}
// start
let context = canvas.getContext("2d");
drawScreen(canvas, context);
}
// write your codes
function drawScreen(canvas, context){
let ball = new Ball();
let easing = 0.05;
let targetX = canvas.width / 2,
targetY = canvas.height / 2;
ball.x = Math.random() * canvas.width;
ball.y = Math.random() * canvas.height;
(function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x += (targetX - ball.x) * easing;
ball.y += (targetY - ball.y) * easing;
ball.draw(context);
} ())
}
})();
</script>
<script>
function Ball(radius, color) {
if (radius === undefined) {
radius = 40;
}
if (color === undefined) {
color = "#ff0000";
}
this.x = 0;
this.y = 0;
this.color = color;
this.radius = radius;
}
Ball.prototype.draw = function(context) {
context.save();
context.translate(this.x, this.y);
context.fillStyle = this.color;
context.beginPath();
context.arc(0, 0, this.radius, 0, 360 * Math.PI / 180, false);
context.closePath();
context.fill();
context.restore();
}
Ball.prototype.getBounds = function() {
return {
x: this.x - this.radius,
y: this.y - this.radius,
width: this.radius * 2,
height: this.radius * 2
};
}
</script>
</body>
</html>