What is the best way to expand this HTML5 canvas script to fill the entire screen?

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:

Answer №1

If you're looking to make your script automatically determine the screen size and adjust the canvas to fill the entire screen rather than being fixed at 500 x 500, you can achieve this programmatically.

To determine the viewport size dynamically, you can use the following code to get the width and height accurately. (Source):

var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

Once you have the viewport dimensions, you can then set the canvas size accordingly:

canvas.width  = width;
canvas.height = height;

So, in your case, the complete code would look something like this:

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Canvas Sizing with Starfield Effect</title>
    <script>
        window.onload = function() {

            /* --- config start --- */

            var starfieldCanvasId     = "starfieldCanvas", // ID of the canvas to use
                framerate             = 60,                // Frames per second for the animation
                numberOfStarsModifier = 0.15,              // Number of stars, performance impact consider
                flightSpeed           = 0.003;             // Speed of flight, adjust for desired speed

            var width = window.innerWidth
            || document.documentElement.clientWidth
            || document.body.clientWidth;

            var height = window.innerHeight
            || document.documentElement.clientHeight
            || document.body.clientHeight;

            /* ---- config end ---- */

            var canvas        = document.getElementById(starfieldCanvasId),
                context       = canvas.getContext("2d"),
                stars         = [],
                TWO_PI        = Math.PI * 2;

                canvas.width  = width;
                canvas.height = height;

                numberOfStars = width * height / 1000 * numberOfStarsModifier;
                dirX          = width / 2;
                dirY          = height / 2;

            // Initialize starfield
            for(var x = 0; x < numberOfStars; x++) {
                stars[x] = {
                    x: range(0, width),
                    y: range(0, height),
                    size: range(0, 1)
                };
            }

            // When mouse moves over canvas, change the center point of animation
            canvas.onmousemove = function(event) {
                dirX = event.offsetX,
                dirY = event.offsetY;
            }

            // Start animation with specified FPS
            window.setInterval(tick, Math.floor(1000 / framerate));

            // Main animation loop
            function tick() {
                var oldX,
                    oldY;

                // Clear canvas for next frame
                context.clearRect(0, 0, width, height);

                for(var x = 0; x < numberOfStars; x++) {
                    // Save old position
                    oldX = stars[x].x;
                    oldY = stars[x].y;

                    // Update star 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;

                    // Reset star if out of bounds
                    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 the 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 a random number within a range
            function range(start, end) {
                return Math.random() * (end - start) + start;
            }
        };
    </script>
</head>
<body style="background:#000;">
    <canvas id="starfieldCanvas"></canvas>
</body>
</html>

I've also tested this on Fiddle. You can view it here: Fiddle

Hopefully, this solution works for you. Feel free to let me know if it does!.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. https://i.sstat ...

Is there a way to send an Ajax response to the web browser client as a downloadable file?

In my MVC 3 project, I have generated a csv file in an Action Method on the server named GetCSV() which is designated as an [HttpPost] action method. My goal is to send this csv file directly to the web browser for download. While I was able to achieve t ...

Resizing images within a container using Bootstrap to fit the screen dimensions

I am having an issue with my bootstrap page where the tiles adjust position based on screen size. Everything works well except when I try to add images to the tiles along with other content. In the example below, you can see that the first tile has an imag ...

Accessing values from a JSON object in AngularJS without using a loop based on another field

Is there a way to extract the "value" associated with the "name" in JSON using Angular JS without having to iterate through the array? For instance, if I have an array like the one below with name and value fields, how can I retrieve the value "ABC" based ...

React.js Material UI Dropdown Component

Is it possible to modify the behavior of the dropdown in Material UI Select? I would like to customize the appearance of <ul> so that it does not resemble a pop-up. My goal is for the selected item to be contained within the <li> element, simi ...

Unfolding the potential of variables in JSON.stringify with Node.js

I am currently developing a node.js API for my app, which includes a simple TCP server that accepts NDJSON (newline delimited JSON). However, I have encountered an issue with the JSON stringify method. The problem arises when I attempt to expand all variab ...

Add the onmouseover attribute to dynamically alter the text

I'm trying to add the onmouseover function to the image of Angelina Jolie in order to change the text above, which currently says "Your Daily Dose of Contrabang". What is the best way to achieve this? Thank you for your assistance. You can check out t ...

No changes occur within this JavaScript code

I am currently working on a piece of Java Script code: document.onreadystateChange = function() { if (document.readystate === "complete") { var menu = document.getElementsByClassName('menu'); var b0 = menu[0]; b0.addE ...

Is there a simple method in JavaScript to combine, structure, and join numerous multi-dimensional arrays in a specific manner (from right to left)?

Looking for a simple solution to merge, flatten, and concatenate multiple multi-dimensional arrays in JavaScript in a specific manner (from right to left) # Example [['.class1', '.class2'], ['.class3', ['.class4', & ...

Submitting a Django POST request with an empty form in an HTML form

When I try to submit a simple HTML form, both request.body and request.POST are empty for some unknown reason. The HTML code for the form is as follows: <div id="signup"> <h1>Sign Up for Free</h1> <form action="/accounts ...

Validation of forms using ajax and javascript

I have implemented ajax on my webpage to dynamically change the content of a main div when different fields in the navigation bar are clicked. However, I am encountering a problem with form validation using JavaScript on elements loaded via ajax. For insta ...

Choosing the right option with the GeoPlugin technology

I am implementing the location detection feature using the plugin. I have a dropdown menu of states represented by <select>, and utilizing jQuery, I automatically select the user's detected state. $.getJSON(url, function(data){ var state = ...

Angular Reactive Forms may not properly update other inputs when binding a control to multiple inputs

While working with reactive forms, I encountered an issue where accessing the same control in multiple inputs seemed to result in one-way data binding (input-to-model). If I make edits in one input, it updates the model correctly but does not refresh the o ...

Instructions for securing a React Front End with Node.js Express-Sessions authentication:

I have decided to move away from using Firestore auth in order to develop my own authentication system. Here is my goal: To create a React web app that allows users to sign up and sign in. Authenticated users should be able to interact with a REST API, w ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

How to incorporate an icon into a React Bootstrap Dropdown menu

I'm struggling to figure out how to include an icon in my react dropdown button, similar to the one shown in the following example. https://i.sstatic.net/cn0b0.png The react bootstrap package I am currently using does not seem to offer a straightfor ...

Locate elements based on an array input in Mongoose

Define the Model: UserSchema = new Schema({ email: String, erp_user_id:String, isActive: { type: Boolean, 'default': true }, createdAt: { type: Date, 'default': Date.now } }); module.export ...

Move the button above a hyperlink in a Bootstrap carousel

Is there a way to add a top-right button on each slide that will be positioned over the carousel-control link? How can I achieve this design? Currently, the buttons appear under the carousel-control as shown below: .myButton { position: absolute; ...

Step-by-step guide on implementing a real-time data array counter in React js

I am attempting to create a function that continuously generates new data arrays with an increasing counter. Each second, a new array should be added with the next number in sequence. data={[ { x: 1, y: 1 }, { x: 2, y: 2 }, ...

Leveraging tailwind for achieving dynamic height responsiveness

My Tailwind-built page currently has a table in the bottom left corner that is overflowing, and I would like it to adjust its size to fit the available space and scroll from there. I want it to fit snugly in the bottom left corner of the browser viewport ...