I am having issues adjusting the canvas to fill the entire window. Currently, it is set to 500x500. As a beginner in coding, any assistance would be greatly appreciated! Thank you.
Below is the code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Creating a Starfield Effect in HTML 5</title>
<script>
window.onload = function() {
/* --- configuration start --- */
var starfieldCanvasId = "starfieldCanvas", // id of the canvas for the starfield
framerate = 60, // frames per second of the animation
numberOfStarsModifier = 0.15, // Number of stars, affects performance
flightSpeed = 0.003; // speed of the flight across the canvas
/* --- configuration end --- */
var canvas = document.getElementById(starfieldCanvasId),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
numberOfStars = width * height / 1000 * numberOfStarsModifier,
dirX = width / 2,
dirY = height / 2,
stars = [],
TWO_PI = Math.PI * 2;
// initializing starfield
for(var x = 0; x < numberOfStars; x++) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: range(0, 1)
};
}
// change animation center on mouse move
canvas.onmousemove = function(event) {
dirX = event.offsetX,
dirY = event.offsetY;
}
// initiate animation loop at specified fps
window.setInterval(tick, Math.floor(1000 / framerate));
// main animation loop
function tick() {
var oldX,
oldY;
// reset canvas for next frame
context.clearRect(0, 0, width, height);
for(var x = 0; x < numberOfStars; x++) {
// save current position
oldX = stars[x].x;
oldY = stars[x].y;
// calculate new position
stars[x].x += (stars[x].x - dirX) * stars[x].size * flightSpeed;
stars[x].y += (stars[x].y - dirY) * stars[x].size * flightSpeed;
stars[x].size += flightSpeed;
// if star is out of bounds, reset
if(stars[x].x < 0 || stars[x].x > width || stars[x].y < 0 || stars[x].y > height) {
stars[x] = {
x: range(0, width),
y: range(0, height),
size: 0
};
}
// draw star
context.strokeStyle = "rgba(255, 255, 255, " + Math.min(stars[x].size, 1) + ")";
context.lineWidth = stars[x].size;
context.beginPath();
context.moveTo(oldX, oldY);
context.lineTo(stars[x].x, stars[x].y);
context.stroke();
}
}
// generate random number within a range
function range(start, end) {
return Math.random() * (end - start) + start;
}
};
</script>
</head>
<body style="background:#000;">
<canvas width="500" height="500" id="starfieldCanvas"></canvas>
</body>
</html>
Original code and credits: