JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
W = canvas.width = window.innerWidth,
H = canvas.height = window.innerHeight,
particles = [],
numParticles = W / 4;
function Particle() {
this.x = Math.random() * W;
this.y = Math.random() * H;
this.vx = Math.random() * 5 + 0.05;
this.vy = Math.random() * 5 + 0.05;
this.radius = Math.random() * 10 + 0.5;
this.color = 'orange';
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
};
Particle.prototype.update = function() {
for (var i = 0; i < particles.length; i++) {
var dx = particles[i].x - this.x,
dy = particles[i].y - this.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < particles[i].radius + (this.radius + 50)) {
ctx.moveTo(this.x, this.y);
ctx.lineTo(particles[i].x, particles[i].y);
ctx.strokeStyle = 'orange';
ctx.stroke();
}
}
this.x += this.vx;
this.y += this.vy;
if (this.x - this.radius / 2 > W) {
this.x = -this.radius / 2;
this.reset();
} else if (this.x + this.radius / 2 < 0) {
this.x = W + this.radius / 2;
this.reset();
}
if (this.y - this.radius / 2 > H) {
this.y = -this.radius / 2;
this.reset();
} else if (this.y + this.radius / 2 < 0) {
this.y = H + this.radius / 2;
this.reset();
}
};
for (var i = 0; i < numParticles; i++) {
particles.push(new Particle());
}
Particle.prototype.reset = function() {
this.vx = Math.random() * 5 + 0.05;
this.vy = Math.random() * 5 + 0.05;
};
;
(function drawFrame() {
requestAnimationFrame(drawFrame);
ctx.clearRect(0, 0, W, H);
for (var i = 0; i < particles.length; i++) {
particles[i].draw();
particles[i].update();
}
})();