# 11、《每周一点canvas动画》 —— 弹性动画

1. 简单的弹性动画

2. 鼠标跟随弹性动画

3. offset spring

4. 总结

### 1.简单的弹性动画

<canvas id="canvas" width="500" height="500" style="background-color: #000;">
</canvas>

<script type="text/javascript" src="../js/utils.js"></script>
<script type="text/javascript" src="../js/ball.js"></script>
<script>
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
spring = 0.03,  //弹性系数
targetX = canvas.width / 2,  //目标位置
f = 0.95,
vx = 0;

ball.y = canvas.height / 2;

(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

var dx = targetX - ball.x,  //目标位置减去小球的位置
ax = dx * spring;  //距离乘以弹性系数

vx += ax;
vx *= f;
ball.x += vx;
ball.draw(context);
}());
};
</script>


var targetX = somewhere;
var targetY = somewhere;

var dx = targetX - ball.x,
ax = dx * spring;
var dy = targetY - ball.y,
ay = dy * spring;

vx += ax;
vy += ay;


### 2.鼠标跟随弹性动画

window.onload = function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
ball = new Ball(20,"orange"),
spring = 0.03, //弹性系数
friction = 0.95, //摩擦力
vx = 0,
vy = 0;

(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);

var dx = mouse.x - ball.x,  //核心代码
dy = mouse.y - ball.y,
ax = dx * spring,
ay = dy * spring;

vx += ax;
vy += ay;
vx *= friction;
vy *= friction;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
}

##### 2.1绳球运动

 。。。
context.save();
context.beginPath();
context.strokeStyle = "#fff";
context.moveTo(ball.x, ball.y);
context.lineTo(mouse.x, mouse.y);
context.stroke();
context.closePath();
context.restore();
。。。

### 4.缓动动画与弹性动画总结

##### 1、缓动动画
var dx = targetX - object.x,
dy = targetY - object.y;

var vx = dx * easing,
vy = dy * easing;

object.x += vx;
object.y += vy;

##### 2、缓动动画，精简形式
object.x += (targetX - object.x) * easing;
object.y += (targetY - object.y) * easing;

##### 3、弹性动画
var ax = (targetX - object.x) * spring;
var ay = (targetY - object.y) * spring;

var vx += ax;
var vy += ay;

vx *= f;
vy *= f;

object.x += vx;
object.y += vy;

##### 4、弹性动画,精简形式
vx += (targetX - object.x) * spring;
vy += (targetY - object.y) * spring;

object.x += (vx*=f);
object.y += (vy*=f);

##### 5、 Offset spring
var dx = object.x - fixedX,
dy = object.y - fixedY;
angle = Math.atan2(dy, dx);
targetX = fixed + Math.cos(angle)*springLength,
targetY = fixed + Math.sin(angle)*springLength;

//spring to targetX, targetY as above