Skip to content

Instantly share code, notes, and snippets.

@bzdgn
Last active December 14, 2016 20:15
Show Gist options
  • Save bzdgn/b037fe1955ef7621b3a73def46c74eb2 to your computer and use it in GitHub Desktop.
Save bzdgn/b037fe1955ef7621b3a73def46c74eb2 to your computer and use it in GitHub Desktop.
2D Stars Demo with HTML5 Canvas
<!DOCTYPE html>
<html>
<head>
<title>Stars Oldskool Demo</title>
</head>
<body>
<canvas width="800" height="800" id="mainCanvas">
</canvas>
<p><input type="Button" VALUE=" start " onClick="doTimer()"></p>
<p><input type="Button" VALUE=" stop " onclick="stopTimer()"></p>
<script>
<!-- Written by Levent Divilioglu -->
<!-- 14.12.2016 -->
<!-- To be fixed: Velocity should be calculated paralel to initial dot coordinates -->
(function () {
canvas = document.getElementById('mainCanvas');
ctx = canvas.getContext("2d");
WIDTH = canvas.width;
HEIGHT = canvas.height;
ctx.fillStyle="black";
ctx.fillRect( 0, 0, WIDTH, HEIGHT);
numberOfStars = 50;
MAX_VELOCITY = 8;
creationBoxLength = 5;
centerX = WIDTH / 2;
centerY = HEIGHT / 2;
stars = generateStars(numberOfStars, creationBoxLength);
})();
function drawStars() {
for(var i = 0; i < stars.length; i++) {
ctx.fillStyle = "white";
ctx.fillRect(stars[i].x, stars[i].y, 3, 3);
}
}
function handleStars() {
for(var i = 0; i < stars.length; i++) {
stars[i].x += stars[i].v_x;
stars[i].y += stars[i].v_y;
if(
(stars[i].x < 0 || stars[i].x > WIDTH)
||
(stars[i].y < 0 || stars[i].y > HEIGHT)
) {
stars[i].x = centerX + getRandom(creationBoxLength);
stars[i].y = centerY + getRandom(creationBoxLength);
stars[i].v_x = getRandom(MAX_VELOCITY);
stars[i].v_y = getRandom(MAX_VELOCITY);
}
}
};
function animateStars() {
clearScreen();
drawStars();
handleStars();
};
function clearScreen() {
ctx.clearRect( 0, 0, WIDTH, HEIGHT );
ctx.fillStyle="black";
ctx.fillRect( 0, 0, WIDTH, HEIGHT );
}
function doTimer() {
timerID = setInterval( "animateStars()", 20 );
}
function stopTimer() {
clearInterval( timerID );
}
function generateStars(numberOfStars, creationBoxLength) {
var stars = [];
for(i = 0; i < numberOfStars; i++) {
var x = centerX + getRandom(creationBoxLength);
var y = centerY + getRandom(creationBoxLength);
stars.push({"starIndex":i, "x":x, "y":y, "v_x": getRandom(MAX_VELOCITY), "v_y": getRandom(MAX_VELOCITY)});
}
return stars;
}
function getRandom(limit) {
var sign = Math.ceil( Math.random() * 100 );
if(sign < 50)
sign = -1;
else
sign = 1;
var num = sign * Math.ceil( (Math.random() * limit-1) + 1);
return num;
}
</script>
</body>
</html>
@bzdgn
Copy link
Author

bzdgn commented Dec 13, 2016

Here is a sample screenshot;

sample

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment