Skip to content

Instantly share code, notes, and snippets.

@ElemarJR
Created October 21, 2011 22:59
Show Gist options
  • Save ElemarJR/1305213 to your computer and use it in GitHub Desktop.
Save ElemarJR/1305213 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
*
{
margin: 0;
padding: 0;
}
html, body
{
height: 100%;
width: 100%;
}
canvas
{
display:block;
background: #000;
}
</style>
</head>
<body>
<canvas id="target">
</canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var canvas = $("#target");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
$(window).resize(resizeCanvas);
function resizeCanvas() {
canvas.attr("width", $(window).get(0).innerWidth);
canvas.attr("height", $(window).get(0).innerHeight);
canvasWidth = canvas.width();
canvasHeight = canvas.height();
};
resizeCanvas();
function randomInRange(min, max) {
return Math.abs(Math.random()) * (max - min) + min;
}
function Star() {
this.x = randomInRange(-20, 20);
this.y = randomInRange(-20, 20);
this.z = randomInRange(0, 32);
this.size = 0;
this.shade = 0;
this.update = function () {
with (this) {
z -= 0.2;
if (z <= 0) {
x = randomInRange(-20, 20);
y = randomInRange(-20, 20);
z = 32;
}
size = (1 - z / 32.0) * 5;
shade = parseInt((1 - z / 32.0) * 255);
}
};
this.draw = function () {
k = 128 / this.z;
px = this.x * k + (canvasWidth / 2);
py = this.y * k + (canvasHeight / 2);
if (px >= 0 && px <= canvasWidth && py >= 0 && py <= canvasHeight) {
context.fillStyle = "rgb(" +
this.shade + ", " +
this.shade + ", " +
this.shade + ")";
context.fillRect(px, py, this.size, this.size);
}
};
}
var stars = new Array(512);
function loadContent() {
for (var i = 0; i < stars.length; i++)
stars[i] = new Star();
animate();
}
loadContent();
function animate() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
for (var i = 0; i < stars.length; i++) {
stars[i].update();
stars[i].draw();
}
setTimeout(animate, 33);
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment