JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
(function() {
'use strict';
function Curve(pos1, pos2, ctrlPos) {
this.pos1 = pos1;
this.pos2 = pos2;
this.ctrlPos = ctrlPos;
this.vx = 0;
this.vy = 0;
this.lineWidth = 0.1 + Math.random() * 0.1;
this.oldPosX = ctrlPos.x;
this.oldPosY = ctrlPos.y;
}
Curve.prototype = {
constructor: Curve,
render: function(ctx) {
ctx.save();
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = '#fff';
ctx.beginPath();
ctx.moveTo(this.pos1.x, this.pos1.y);
ctx.quadraticCurveTo(this.ctrlPos.x, this.ctrlPos.y, this.pos2.x, this.pos2.y);
ctx.stroke();
/*
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(this.ctrlPos.x, this.ctrlPos.y, 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
*/
}
}
var canvas, ctx, width, height, curves, mouse;
init();
function init() {
canvas = document.createElement('canvas');
ctx = canvas.getContext('2d');
width = canvas.width = window.innerWidth;
height = canvas.height = window.innerHeight;
curves = [];
mouse = getMousePos(canvas);
//canvas.style.margin = -canvas.height / 2 + 'px 0px 0px ' + -canvas.width / 2 + 'px';
document.body.appendChild(canvas);
generateCurves(width, 20, 'vertical');
generateCurves(height, 20, 'horizontal');
ctx.fillStyle = '#17293a';
renderFrame();
}
function generateCurves(range, spacing, type) {
var curve, index, x, y;
if (type === 'horizontal') {
index = height / 2;
for (y = height / 2 - range / 2; y <= height / 2 + range / 2; y += spacing) {
curve = new Curve({
x: 0,
y: y
}, {
x: width,
y: y
}, {
x: width / 2,
y: (index)
});
curves.push(curve);
index += 2;
}
} else if (type === 'vertical') {
index = width / 2;
for (x = width / 2 - range / 2; x <= width / 2 + range / 2; x += spacing) {
curve = new Curve({
x: x,
y: 0
}, {
x: x,
y: height
}, {
x: (index),
y: height / 2
});
curves.push(curve);
index += 2;
}
}
}
function renderFrame() {
window.requestAnimFrame(renderFrame, canvas);
ctx.fillRect(0, 0, width, height);
curves.forEach(renderCurve);
}
function renderCurve(curve) {
var speed, gravity,
dx, dy,
dist, maxDist;
speed = 0.2;
gravity = 0.88;
dx = mouse.x - curve.ctrlPos.x;
dy = mouse.y - curve.ctrlPos.y;
dist = Math.sqrt(dx * dx + dy * dy);
maxDist = width / 3;
if (dist <= maxDist) {
curve.vx += dx * speed;
curve.vy += dy * speed;
} else {
curve.vx += (curve.oldPosX - curve.ctrlPos.x) * speed;
curve.vy += (curve.oldPosY - curve.ctrlPos.y) * speed;
}
curve.vx *= gravity;
curve.vy *= gravity;
curve.ctrlPos.x += curve.vx;
curve.ctrlPos.y += curve.vy;
curve.render(ctx);
}
function getMousePos(element) {
var mouse = {
x: width / 2,
y: height / 2
};
element.addEventListener('mousemove', function(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}, false);
return mouse;
}
})();