Life Forms?
by Admiral Potato
HTML
<canvas id="space" width="800" height="400"></canvas>
CSS
body{
background-color: #000;
}
#space{
border: 1px solid #333;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
JavaScript
var canvas = document.getElementById('space'),
context = canvas.getContext('2d'),
width = canvas.width,
half = width / 2,
posRange = function(){
return half - width * Math.random();
},
pi = Math.PI,
tau = pi * 2,
deg = tau / 360,
vAdd = function(a, b, c){
var destination = c || a;
destination.x = a.x + b.x;
destination.y = a.y + b.y;
return destination;
},
vSet = function(angle, radius, out){
angle = angle || 0;
radius = radius || 1;
out = out || {};
out.x = Math.cos(angle) * radius;
out.y = Math.sin(angle) * radius;
return out;
},
drawX = function(pos, crossWidth){
crossWidth = crossWidth || 5;
context.save();
context.translate(pos.x, pos.y);
context.strokeStyle = '#fff';
context.beginPath();
context.moveTo(-crossWidth, -crossWidth);
context.lineTo(crossWidth, crossWidth);
context.stroke();
context.beginPath();
context.moveTo(crossWidth, -crossWidth);
context.lineTo(-crossWidth, crossWidth);
context.stroke();
context.restore();
};
var Part = function(){
};
Part.prototype = {
render: function(){}
};
var LifeForm = function(){
var t = this;
t.pos = {
x: posRange(),
y: posRange()
};
t.angle = tau * Math.random();
t.vel = vSet(t.angle, 1, t.vel);
};
LifeForm.prototype = {
update: function(){
var t = this;
t.angle += (Math.random() - 0.5) * 0.3;
t.vel = vSet(t.angle, 1, t.vel);
vAdd(t.pos, t.vel);
},
render: function(){
drawX(this.pos);
}
};
var objectList = [];
var frame = function(){
context.save();
context.translate(half, 0);
objectList.forEach(function(item){
item.update();
});
objectList.forEach(function(item){
item.render();
});
context.restore();
var result = window.requestAnimationFrame(frame);
//console.log(result, arguments);
};
for(var i = 0; i < 30; i++){
objectList.push(new LifeForm());
}
window.requestAnimationFrame(frame);