verlet.js 源码分析--二次开发
本系列文章可以在这里查看:verletjs动画框架
你可以从这里查看该项目的所有源文件:https://github.com/subprotocol/verlet-js
涉及文件:lib/verlet.js
, lib/object.js
如上一节所讲,基于该动画引擎的二次开发就是给VerletJS对象新加方法。把自定义动画的粒子对象,约束对象都放到统一的集合中。最后调用VerletJS的frame方法和draw方法重绘即可。
下面以开发一个画圆API为例进行二次开发讲解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 画圆API
* @param {Vec2} origin 圆心
* @param {Number} radius 半径
*/
VerletJS.prototype.circle = function(origin, radius) {
// 用于存储所有的组合对象
this.composite = new this.Composite();
// 把圆心粒子对象存储到集合中,供draw的时候使用
composite.particles.push(new Particle(new Vec2(origin.x, origin.y)));
this.composites.push(composite);
// 返回该组合对象,用于重写draw方法
return composite;
}
var sim = new VerletJS(width, height, canvas);
var circle = sim.circle(new Vec2(100, 100), 10);
// 重写draw方法,这里的draw方法用于画圆
circle.drawParticles = function(ctx, composite) {
var i;
for (i in composite.particles) {
var point = composite.particles[i];
ctx.beginPath();
ctx.arc(point.pos.x, point.pos.y, 10, 0, Math.PI * 2);
ctx.strokeStyle = "#369";
ctx.stroke();
}
}
// 在画布上持续执行动画
(function loop() {
sim.frame(16);
sim.draw();
window.requestAnimationFrame(arguments.callee);
})();
至此,本系列教程完结!!!
- 上一篇:verlet.js 源码分析--API
- 下一篇:彻底搞懂浏览器端的缓存