Grid Particle Animation
HTML
<canvas id="canvas" style="height:100%">
当前浏览器不支持Canvas,请更换浏览器后再试
</canvas>
CSS
#canvas {
position: absolute;
display: block;
left: 0;
top: 0;
background: #0f0f0f;
z-index: -1;
}
JavaScript
'use strict';
function CanvasAnimation(canvas, options, generator) {
// ============== 辅助函数 =================
window.requestAnimFrame = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function ( /* function FrameRequestCallback */ callback, /* DOMElement Element */
element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
var extend = function (o, n) {
for (var p in n) {
if (n.hasOwnProperty(p) && o.hasOwnProperty(p)) {
o[p] = n[p];
}
}
}
this.delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
// ========================================
this.opts = {
width: 800,
height: 600,
dt: 1000 / 60
}
extend(this.opts, options);
canvas.width = this.opts.width;
canvas.height = this.opts.height;
this.objs = {};
this.objs.canvas = canvas;
this.objs.context = canvas.getContext("2d");
this.objs.canvasElement = [];
this.objs.lastTime = 0;
this.objs.acc = 0;
this.objs.isRunning = false;
this.objs.generator = generator;
this.objs.generator.init(this, this.opts.width, this.opts.height);
var that = this;
this.mainLoop = function () {
if (that.objs.isRunning) {
window.requestAnimationFrame(that.mainLoop);
}
var now = Date.now();
var deltaTime = now - that.objs.lastTime;
that.objs.lastTime = now;
that.objs.acc += deltaTime;
while (that.objs.acc >= that.opts.dt) {
update(that.opts.dt);
that.objs.acc -= that.opts.dt;
}
...