Stars
The HTML file:
<html>
<head>
<script src="stars.js" defer></script>
</head>
<body>
<canvas id="sky"
width="100"
height="100"
style="border:1px solid black;"></canvas>
<p>
<button type="button" id="start"> Start</button>
<button type="button" id="end" disabled="true"> End</button>
</body>
</html>
stars.js
"use strict"
const STAR_COUNT = 50;
const MAX_SIZE = 5;
let starArray = [];
// canvas stuff
const canvas = document.getElementById("sky");
const context = canvas.getContext("2d");
const height = canvas.height = 400;
const width = canvas.width = 400;
// button stuff
const StartButton = document.getElementById("start");
const EndButton = document.getElementById("end");
const colors = ["red", "green", "blue", "cyan", "magenta", "yellow"];
context.clearRect(0,0,width, height);
function RandomInt(max) {
return Math.floor(Math.random() * max);
}
function RandomColor() {
const size = colors.length
return colors[RandomInt(size)]
}
function CreateStars() {
if (starArray.length !== 0) {
starArray = []
}
for (let i = 0; i < STAR_COUNT; ++i) {
let star = {x: RandomInt(width),
y: RandomInt(height),
color : RandomColor(),
size: RandomInt(MAX_SIZE)+1,
growing : RandomInt(2) == 1}
starArray.push(star);
}
}
function DisplayStars() {
context.fillStyle = "black";
context.fillRect(0,0,width, height)
for (let star of starArray) {
context.fillStyle = star.color;
context.fillRect(star.x, star.y, star.size, star.size);
}
}
function ChangeStars() {
let change;
// switch directions if needed
for (let i in starArray) {
if ((starArray[i].size <= 0 && !starArray[i].growing)
|| (starArray[i].size >= MAX_SIZE && starArray[i].growing)) {
starArray[i].growing = !starArray[i].growing
}
if (starArray[i].growing ) {
change = 1;
} else {
change = -1;
}
starArray[i].size += change;
}
}
function DoStep() {
ChangeStars()
DisplayStars();
}
let timer;
let running = false;
function StartAnimation() {
if (running == false) {
running = true;
timer = setInterval(DoStep, 150);
StartButton.disabled = true;
EndButton.disabled = false;
}
}
function StopAnimation() {
if (running == true) {
running = false;
clearInterval(timer);
StartButton.disabled = false;
EndButton.disabled = true;
}
}
CreateStars();
DisplayStars();
// make sure the timer is in sync with the program
StartButton.addEventListener("click", StartAnimation);
StartButton.disabled = false;
EndButton.addEventListener("click", StopAnimation);
EndButton.disabled = true;