# 【canvas】动画原理の胡克定律

·  阅读 7544

### 1. 运动学一般原理

``````ball.x += 3
ball.y += 4

``````vx = 3
vy = 4
ball.x += vx
ball.y += vy

``````ax = 0.5
ay = 1
vx += ax
vy += ay
ball.x += vx
ball.y += vy

f = m * a

``````vx = 2.5
vy = -6
gravity = 0.1
vy += gravity
ball.x += vx
ball.y += vy

``````class Ball{
constructor() {
this.x = 0
this.y = 0
}
draw(context) {
context.save()
context.translate(this.x, this.y)
context.fillStyle = 'red'
context.beginPath()
context.arc(0, 0, this.radius, 0, Math.PI * 2)
context.fill()
context.restore()
}
}

``````friction = 0.99
vx *= friction
vy *= friction
ball.x += vx
ball.y += vy

### 2. 胡克定律

F = k * x

f = -k * x

``````var x = ball.x -spring.x - initLength
var f = -k * x
vx += f
ball.x += vx
spring.length = ball.x - spring.x

``````var amplitude = 70
ball.x += amplitude
var vx = 0

``````class Spring{
constructor(length) {
this.x = 0
this.y = 0
this.angle = 0
this.length = length
}
draw(context) {
context.save()
context.translate(this.x, this.y)
context.rotate(this.angle)
context.strokeStyle = 'white'
context.beginPath()
context.moveTo(0, 0)
var n = 16
var h = 25
var d = (this.length - 2 * h) / n
context.lineTo(h, 0)
for (var i = 0; i < n; i++) {
var dir = i % 2 == 0 ? 1 : -1
context.quadraticCurveTo(h + d * ( i + 0.5), 20 * dir,  h + d * (i + 1), 0)
}
context.lineTo(this.length, 0)
context.stroke()
context.restore()
}
}

### 3. 力的合成与分解

``````spring.x = mouse.x
spring.y = mouse.y

``````var dx = ball.x - spring.x
var dy = ball.y - spring.y
var x = Math.sqrt(dx * dx + dy * dy) - initLength
var f = -k * x

``````var angle = Math.atan2(dy, dx)
var fx = f * Math.cos(angle)
var fy = f * Math.sin(angle)

``````vx += fx
vy += fy
vy += gravity
vx *= friction
vy *= friction
ball.x += vx
ball.y += vy

2019年末，本人立了个flag，2020年要研究透canvas动画技术。

（图中二维码是我的唯一微信号，如有掘友想加的，麻烦备注下【掘金】哈。）