JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
function Ball(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
this.vx = 20;
this.vy = 10;
}
Ball.prototype.draw = function(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.restore();
}
function Curve(points) {
this.points = points;
this.ballRadius = 5;
this.speed = 0.12;
this.vy = 2 + Math.random() * 2;
}
Curve.prototype.draw = function() {
var length = this.points.length - 2,
ctrlPoint = {},
i;
ctx.save();
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
for (i = 1; i < length; i++) {
ctrlPoint.x = (this.points[i].x + this.points[i + 1].x) / 2;
ctrlPoint.y = (this.points[i].y + this.points[i + 1].y) / 2;
ctx.quadraticCurveTo(this.points[i].x, this.points[i].y, ctrlPoint.x, ctrlPoint.y);
}
ctx.quadraticCurveTo(this.points[i].x, this.points[i].y, this.points[i + 1].x, this.points[i + 1].y);
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.strokeStyle = '#fff';
ctx.stroke();
ctx.restore();
}
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
W = canvas.width = window.innerWidth,
H = canvas.height = window.innerHeight,
limit = W / 2.2,
horizontalBall = new Ball(100, H / 2, 100),
curves = [];
for (var y = H / 2 - 150; y <= H / 2 + 150; y += 50) {
makeCurve(y)
}
function makeCurve(y) {
var curve, points = [];
for (var x = W / 2 - limit; x <= W / 2 + limit; x += 100) {
points.push({
x: x,
y: y,
oldY: y,
targetY: y - 300 + Math.random() * 600,
speed: 0.1,
vy: 5 + Math.random() * 5,
gravity: 0.85,
vyy: 3 + Math.random() * 4
});
}
curve = new Curve(points);
curves.push(curve)
}
function moveBalls(ball) {
if (ball == horizontalBall) {
if (ball.x + ball.radius > W) {
ball.x = W - ball.radius - 50;
ball.vx *= -1;
} else if (ball.x - ball.radius < 0) {
ball.x = 50 + ball.radius;
ball.vx *= -1;
}
ball.x += ball.vx;
}
}
(function drawFrame() {
requestAnimationFrame(drawFrame, canvas);
ctx.fillStyle = '#17293a';
ctx.fillRect(0, 0, W, H);
curves.forEach(function(curve) {
curve.points.forEach(function(point) {
var dx, dy, dist,
dx2, dy2, dist2,
n = curve.points.indexOf(point);
dx = (horizontalBall.x - point.x);
dy = (horizontalBall.y - point.y);
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < 200) {
if (n % 2 === 0) {
point.y -= point.vyy;
} else if (n % 2 !== 0) {
point.y += point.vyy;
}
} else {
point.vy += (point.oldY - point.y) * point.speed;
point.vy *= point.gravity;
point.y += point.vy;
}
});
curve.draw(ctx);
});
moveBalls(horizontalBall);
}());