JavaScript、canvas的缓动
原创
©著作权归作者所有:来自51CTO博客作者我的代码呢的原创作品,请联系作者获取转载授权,否则将追究法律责任
缓动
速度和距离成正比,离目标越近,速度就越慢:
v = l * k
,l表示距离,k是运动的比例系数。
- 定义一个运动的比例系数,大于0,小于1;
- 明确目标点;
- 确定物体和目标之间的距离;
- 计算速度,速度=比例系数*距离;
- 用当前位置加上速度计算出的新位置;
现在来定义运动比例系数 用easing
表示:
确立终点,也就是目标,这里就直接用canvas的中心位置了:
let targetX = canvas.width / 2;
let targetY = canvas.height / 2;
终点和起点的距离怎么算呢?是通过canvas的中心点位置减去物体的初始位置:
let dx = targetX - ball.x ;
let dy = targetY - ball.y ;
那么就可以计算出X和Y轴方向的速度了:
let vx = dx * easing ;
let vy = dy * easing ;
小球运动的时候,也就是小球的位置的变化:
ball.x = ball.x + vx ;
ball.y = ball.y = vy ;
效果如下图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>easing</title>
</head>
<body>
<canvas id='canvas' width="400" height="400" style="border: 1px solid red;"></canvas>
<script src="./js/ball.js"></script>
<script>
window.onload = () => {
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let ball = new Ball(12, 'blue');
let easing = 0.05;
let targetX = canvas.width / 2;
let targetY = canvas.height / 2;
(function drawFrame() {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
let vx = (targetX - ball.x) * easing;
let vy = (targetY - ball.y) * easing;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}())
}
</script>
</body>
</html>