JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var canvas,
ctx,
width,
height,
xCenter,
yCenter,
squares;
function square(opt) {
this.x = opt.x;
this.y = opt.y;
this.size = opt.size;
this.rotation = opt.rotation;
this.hue = opt.hue;
this.speed = opt.speed;
this.angle = this.rotation;
this.scale = 1;
this.xBase = this.x;
this.yBase = this.y;
this.xTarget = this.x + Math.cos(this.angle) * this.speed;
this.yTarget = this.y + Math.sin(this.angle) * this.speed;
}
square.prototype.step = function(i) {
this.rotation -= 0.05;
this.x = this.xBase + (this.xTarget - this.xBase) * (1 + Math.sin(tick / 25));
this.y = this.yBase + (this.yTarget - this.yBase) * (1 + Math.sin(tick / 25));
};
square.prototype.draw = function(i) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.scale(this.scale, this.scale);
ctx.rotate(this.rotation);
ctx.fillStyle = 'hsla( ' + this.hue + ' , 80%, 60%, 1)';
ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size);
ctx.restore();
ctx.save();
ctx.translate(xCenter, yCenter);
ctx.rotate(Math.PI);
ctx.scale(this.scale, this.scale * 1);
ctx.translate(-xCenter + this.x, -yCenter + this.y);
ctx.scale(this.scale, this.scale);
ctx.rotate(this.rotation);
ctx.fillStyle = 'hsla( ' + this.hue + ' , 80%, 60%, 1)';
ctx.fillRect(-this.size / 2, -this.size / 2, this.size, this.size);
ctx.restore();
};
function squareRow(count, size, radius, speed, hue) {
if (count <= 1) return;
for (var i = 0; i < count; i++) {
var angle = (Math.PI + (i / (count - 1)) * Math.PI) || 0,
x = xCenter + Math.cos(angle) * radius,
y = yCenter + Math.sin(angle) * radius;
squares.push(new square({
x: x,
y: y,
size: size,
rotation: angle,
hue: hue,
speed: speed
}));
}
}
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
squares = [];
reset();
loop();
}
function reset() {
width = window.innerWidth;
height = window.innerHeight;
xCenter = width / 2;
yCenter = height / 2;
squares.length = 0;
canvas.width = width;
canvas.height = height;
tick = 0;
}
function create() {
if (tick == 0) {
for (var i = 0, length = 7; i < length; i++) {
var count = 7 + i * 2,
size = 5 + i,
radius = 20 + i * 20,
speed = 30,
hue = 360 - ((i + 1) / length) * 360;
squareRow(count, size, radius, speed, hue);
}
}
}
function step() {
var i = squares.length;
while (i--) {
squares[i].step(i);
}
}
function clear() {
ctx.clearRect(0, 0, width, height);
}
function draw() {
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height / 2);
ctx.fillStyle = '#000';
ctx.fillRect(0, yCenter, width, height / 2);
var i = squares.length;
while (i--) {
ctx.save();
ctx.translate(xCenter, yCenter);
ctx.rotate(tick / 100);
ctx.translate(-xCenter, -yCenter);
squares[i].draw(i);
ctx.restore();
}
}
function loop() {
requestAnimationFrame(loop);
create();
step();
clear();
draw();
tick++;
}
function onresize() {
reset();
}
window.addEventListener('resize', onresize);
init();