JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
var ctx = null,
global = null,
objs = [];
function create_obj() {
return {
x: -20 + Math.random() * 40,
y: -20 + Math.random() * 40,
r: 5 + Math.random() * 10,
p: Math.random() * 360,
d: Math.floor(Math.random() * 2),
s: 0.5 + Math.random(),
move: function() {
this.p += this.d ? -this.s : this.s;
if (this.p >= 360) {
this.d = !this.d;
this.p -= 180;
}
if (this.p <= -180) {
this.d = !this.d;
this.p += 180;
}
},
toGlobal: function() {
var x = (!this.d ? global.x1 : global.x2),
y = global.h / 2,
deg = this.p * Math.PI / 180;
return {
x: x + this.x + global.r * Math.cos(deg),
y: y + this.y + global.r * Math.sin(deg)
};
},
draw: function(ctx, r) {
var glb = this.toGlobal();
ctx.moveTo(glb.x + this.r + r, glb.y);
ctx.arc(glb.x, glb.y, this.r + r, 0, 6.28);
}
};
}
function init() {
s = Math.max(Math.min(window.innerWidth, window.innerHeight), 200);
s = Math.min(s, 600);
global = {
w: s,
h: s,
x1: s / 3,
x2: s * 2 / 3,
r: s / 6
};
var canvas = document.getElementById('frame');
canvas.width = global.w;
canvas.height = global.h;
if (canvas.getContext) {
ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'source-over';
ctx.clearRect(0, 0, global.w, global.h);
}
objs = []
for (var i = 0; i < 100; i++)
objs.push(create_obj());
window.requestAnimationFrame(draw);
}
function draw() {
if (ctx == null) return;
window.requestAnimationFrame(draw);
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.fillRect(0, 0, global.w, global.h);
/* Move */
for (var i = 0; i < objs.length; i++)
var cur = objs[i].move();
/* Draw */
ctx.fillStyle = 'rgba(0, 0, 0, 1)';
ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
ctx.beginPath();
for (var i = 0; i < objs.length; i++)
objs[i].draw(ctx, 0);
ctx.fill();
ctx.stroke();
ctx.fillStyle = 'rgba(255, 255, 255, 1)';
ctx.strokeStyle = 'rgba(255, 255, 255, 1)';
ctx.beginPath();
for (var i = 0; i < objs.length; i++)
objs[i].draw(ctx, -1);
ctx.fill();
ctx.stroke();
}
init();