Skip to content

Commit

Permalink
Starfiled
Browse files Browse the repository at this point in the history
  • Loading branch information
yuki0418 committed Nov 8, 2020
1 parent 82f0982 commit f3b0318
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
2 changes: 2 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@
<a href="./flappy-bird/flappy-bird.html">Flappy Bird</a>
<br>
<a href="./breakout/breakout.html">Breakout</a>
<br>
<a href="./starfield/index.html">Starfield</a>
</body>
</html>
12 changes: 12 additions & 0 deletions starfield/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Starfield</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="./index.js"></script>
</html>
69 changes: 69 additions & 0 deletions starfield/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let stars = [];

function setup() {
canvas.width = 500;
canvas. height = 500;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.translate(canvas.width / 2, canvas.height / 2);

for(let i = 0; i < 125; i++) {
stars.push(new Star());
}
}

function draw() {
clear();

for(let i in stars) {
stars[i].update();
stars[i].show();
}

window.requestAnimationFrame(draw);
}

function clear() {
ctx.fillStyle = 'black';
ctx.fillRect(-canvas.width/2,-canvas.height/2,canvas.width, canvas.height );
}

class Star {
constructor() {
this.x = Math.ceil(Math.random() * canvas.width / 2) * (Math.round(Math.random()) ? 1 : -1);
this.y = Math.ceil(Math.random() * canvas.height / 2) * (Math.round(Math.random()) ? 1 : -1);
this.z = 0.1;
this.speed = 0.01;
}

update() {
this.x += this.x * this.speed;
this.y += this.y * this.speed;
this.z += 0.01;
this.resetPosi();
}

resetPosi() {
if(
this.x < -(canvas.width / 2) || this.x > canvas.width / 2 ||
this.y < -(canvas.height /2) || this.y > canvas.height / 2
) {
this.x = Math.ceil(Math.random() * canvas.width / 5) * (Math.round(Math.random()) ? 1 : -1);
this.y = Math.ceil(Math.random() * canvas.height / 5) * (Math.round(Math.random()) ? 1 : -1);
this.z = 0.01;
}
}

show() {
ctx.fillStyle = 'white';
ctx.beginPath();
ctx.arc(this.x, this.y, this.z, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
}

setup()
window.requestAnimationFrame(draw);

0 comments on commit f3b0318

Please sign in to comment.