JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
// canvas setup //
var w = c.width = window.innerWidth,
h = c.height = window.innerHeight,
ctx = c.getContext('2d'),
// parameters //
dotDistance = 100,
dotRadius = 5,
minProximity = dotDistance * 4,
repaintAlpha = 1,
// other values //
mouse = new Dot(w / 2, h / 2),
dots = [],
prevDD = 0, //dotDistance,
//prevDR = dotRadius,
prevMP = 0, //minProximity,
minProxSquared,
hue = 0,
templateColor = 'hsl( 0, 80%, 50% )',
// gui stuff //
params = ['dotDistance', 'dotRadius', 'minProximity', 'repaintAlpha'],
boundaries = [
[20, 200],
[2, 9],
[40, 600],
[0, 1]
],
gui = new dat.GUI({
autoPlace: false
});
// main functions //
function init() {
for (var i = 0; i < params.length; ++i)
gui.add(window, params[i], boundaries[i][0], boundaries[i][1]);
guiHolder.appendChild(gui.domElement);
considerParameters();
}
function considerParameters() {
if (dotDistance !== prevDD) {
prevDD = dotDistance;
createDots();
}
if (minProximity !== prevMP) {
prevMP = minProximity;
minProxSquared = minProximity * minProximity;
}
render();
}
function createDots() {
dots.length = 0;
for (var x = 0; x < w; x += dotDistance)
for (var y = 0; y < h; y += dotDistance)
dots.push(new Dot(x, y));
}
function updateMouse(e) {
mouse.x = e.clientX;
mouse.y = e.clientY;
hue = ((mouse.x / w + mouse.y / h) * 360) % 360;
templateColor = 'hsl( hue, 80%, brightness% )'
.replace('hue', hue);
render();
}
function render() {
ctx.fillStyle = 'rgba(0, 0, 0, alp)'
.replace('alp', repaintAlpha);
ctx.fillRect(0, 0, w, h);
dots.map(function(dot) {
dot.render();
});
}
// dot constructor //
function Dot(x, y) {
this.x = x;
this.y = y;
}
Dot.prototype.render = function() {
var dX = this.x - mouse.x, // distance X
dY = this.y - mouse.y, // distance Y
distSquared = dX * dX + dY * dY;
if (distSquared <= minProxSquared) {
var brightness = 50 - distSquared / minProxSquared * 40;
ctx.fillStyle = ctx.strokeStyle = templateColor.replace('brightness', brightness);
ctx.beginPath();
ctx.arc(this.x, this.y, dotRadius, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
} else {
ctx.fillStyle = '#222';
ctx.beginPath();
ctx.arc(this.x, this.y, dotRadius, 0, Math.PI * 2);
ctx.fill();
}
}
// document handlers //
window.addEventListener('mousemove', updateMouse);
guiHolder.addEventListener('mousemove', considerParameters);
window.addEventListener('resize', function() {
w = c.width = window.innerWidth;
h = c.height = window.innerHeight;
createDots();
render();
})
// blast off //
init();