# 19、《每周一点canvas动画》——桌球运动(1)

1. 动量

2. 动量守恒

3. 能量守恒

### 1.什么是动量

动量（p）, 质量（m）, 速度（v）

### 2.动量守恒

 m1 * v1 + m2 * v2 = m1 * v1F + m2 * v2F

### 3.能量守恒

E = 0.5 * m * v^2


 (0.5 * m1 * v1^2) + (0.5 * m2 * v2^2) = (0.5 * m1 * v1F^2) + (0.5 * m2 * v2F^2)

ok,有了上面两个公式，我们就可以解出碰撞后的速度

公式1： m1 * v1 + m2 * v2 = m1 * v1F + m2 * v2F

v1F = ((m1 - m2)*v1 + 2*m2*v2) / (m1+m2)
v2F = ((m2 - m1)*v2 + 2*m1*v1) / (m1+m2)

### 4.代码实例

this.mass = 1;

<canvas id="canvas" width="500" height="500" style="background:#000">
</canvas>
<script src="../js/utils.js"></script>
<script src="../js/ball.js"></script>
<script>
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d'),
ball0 = new Ball(),
ball1 = new Ball(20,"red");

//球0
ball0.mass = 2;                  //质量为2
ball0.x = 50;
ball0.y = canvas.height/2;
ball0.vx = 1;

//球1
ball1.mass = 1;                    //质量为1
ball1.x = 400;
ball1.y = canvas.height/2;
ball1.vx = -1;                    //速度为反向，大小为1

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

ball0.x += ball0.vx;
ball1.x += ball1.vx;

var dist = ball1.x - ball0.x;

//计算碰撞后的速度
var vx0Final = ((ball0.mass - ball1.mass)*ball0.vx + 2 * ball1.mass * ball1.vx)/(ball0.mass +ball1.mass);
var vx1Final = ((ball1.mass - ball0.mass)*ball1.vx + 2 * ball0.mass * ball0.vx)/(ball0.mass +ball1.mass);

//控制台打印
console.log(vx0Final, vx1Final);

//重新赋值
ball0.vx = vx0Final;
ball1.vx = vx1Final;

ball0.x += ball0.vx;
ball1.x += ball1.vx;
}

ball0.draw(context);
ball1.draw(context);
}())
}
</script>


    ball0.mass = 3; 

    ball1.vx = -3;

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120