JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
$(document).ready(function() {
// rAF
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
});
// fast absolute value
var fastAbs = function(value) {
return (value ^ (value >> 31)) - (value >> 31);
};
// capture dimesions
var H = $(window).height();
var W = $(window).width();
// setup
var nodes = (W < 960) ? 120 : 200;
var dxy = new Array();
var x = 0,
y = 0;
var s = 2; // speed
var t = 140; // threshold
var ax, ay;
var d = 0.1;
for (var i = 0; i < nodes; i++) {
dxy[i] = [
Math.random() * 360, // random direction vector
(W < 600) ? (W * Math.random()) : (W / 2), (W < 600) ? (H * Math.random()) : (H / 2)
];
}
// canvas setup
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
c.width = W;
c.height = H;
function loop() {
for (var i = 0; i < nodes; i++) {
x = Math.sin(dxy[i][0]) * s + dxy[i][1];
y = Math.cos(dxy[i][0]) * s + dxy[i][2];
x = (x > W + t) ? -t : (x < -t) ? W + t : x;
y = (y > H + t) ? -t : (y < -t) ? H + t : y;
dxy[i][0] = dxy[i][0] + ((Math.random() * 2 - 1) * d);
for (var j = 0; j < nodes; j++) {
ax = fastAbs(x - dxy[j][1]);
ay = fastAbs(y - dxy[j][2]);
if ((ax < t) && (ay < t)) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(dxy[j][1], dxy[j][2]);
if (x < dxy[i][1]) {
ctx.strokeStyle = 'black';
} else {
ctx.strokeStyle = 'white';
}
ctx.globalAlpha = 0.1;
ctx.stroke();
ctx.globalAlpha = 1;
}
}
dxy[i][1] = x;
dxy[i][2] = y;
};
}
// frame requester
function draw() {
requestAnimationFrame(draw);
loop();
}
// pull trigger
draw();
// resize reset
$(window).resize(function() {
H = $(window).height();
W = $(window).width();
c.width = W;
c.height = H;
});
});