實(shí)現(xiàn)緩動(dòng)的策略:
為運(yùn)動(dòng)確定一個(gè)比例系數(shù)旧烧,這是一個(gè)小于1且大于0的小數(shù)
確定目標(biāo)點(diǎn)
計(jì)算出物體與目標(biāo)點(diǎn)的距離- 計(jì)算速度,速度 = 距離 x 比例系數(shù)
用當(dāng)前位置加上速度來計(jì)算新的位置
重復(fù)第三步到第五步,直到物體到達(dá)目標(biāo)
程序?qū)崿F(xiàn):
首先確定一個(gè)比例系數(shù)柿汛,比如設(shè)置為0.05胸嘴,用變量easing表示:
var easing = 0.05;
接著確定目標(biāo)點(diǎn),在這里我們使用canvas元素的中心點(diǎn):
var targetX = canvas.width / 2,
targetY = canvas.height / 2;
然后計(jì)算物體到目標(biāo)點(diǎn)的距離寄锐。假設(shè)這個(gè)物體是一個(gè)小球兵多,我們用ball來表示,小球的位置坐標(biāo)為(x, y)橄仆,目標(biāo)點(diǎn)減去小球所在位置得到距離:
var dx = targetX - ball.x,
dy = targetY - ball.y;
速度就是距離乘以系數(shù):
var vx = dx * easing,
vy = dy * easing;
ball.x += vx;
ball.y += vy;
完整代碼如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Easing</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="js/ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
easing = 0.05, // 比例系數(shù)
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>
javascript部分:
// ball.js
var utils = {
parseColor: function (color, toNumber) {
if (toNumber === true) {
if (typeof color === 'number') {
return (color | 0);
}
if (typeof color === 'string' && color[0] === '#') {
color = color.slice(1);
}
return window.parseInt(color, 16);
}
else {
if (typeof color === 'number') {
color = '#' + ('0000' + (color | 0).toString(16)).substr(-6);
}
return color;
}
}
};
function Ball (radius, color) {
color = color || '#ff0000';
this.radius = radius;
this.color = utils.parseColor(color);
this.x = 0;
this.y = 0;
this.rotation = 0;
this.vx = 0;
this.vy = 0;
this.scaleX = 1;
this.scaleY = 1;
this.lineWidth = 1;
}
Ball.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.rotate(this.rotation);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.fillStyle = this.color;
context.beginPath();
context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
}
context.restore();
}
至此我們已經(jīng)學(xué)習(xí)完了簡(jiǎn)單的緩動(dòng)運(yùn)動(dòng)剩膘。