The Canvas Snow Animation is malfunctioning

Seeking advice for a seasonal query. I have created a simple animation to mimic snowfall. However, the issue is that the snow falls only once and then the screen remains black. I referred to a tutorial that enclosed everything within window.onload(). Nonetheless, I believe there might be a better approach, so here’s my revised solution:

let sky, ctx;
let W, H;

const maxSnow = 250;
const snow = [];

function init(){
sky = document.getElementById("sky");
ctx = sky.getContext("2d");

sky.width = W = window.innerWidth;
sky.height = H = window.innerHeight;

for(let i = 0; i < maxSnow; i++)
{
snow.push({
x: Math.random()*W, //x-coordinate
y: -50, //y-coordinate
radius: Math.random()*4+1, //radius
density: Math.random()*maxSnow //density
})
}
}

function draw()
{
ctx.clearRect(0, 0, W, H);

ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.beginPath();
for(let i = 0; i < maxSnow; i++)
{
var flake = snow[i];
ctx.moveTo(flake.x, flake.y);
ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI*2, true);
}
ctx.fill();
update();
}

var angle = 0;
function update()
{
angle += 0.01;
for(var i = 0; i < maxSnow; i++)
{
var p = snow[i];

p.y += Math.cos(angle+p.density) + 1 + p.radius/2;
p.x += Math.sin(angle) * 2;

if(p.x > W+5 || p.x < -5 || p.y > H)
{
if(i%3 > 0)
{
snow[i] = {x: Math.random()*W, y: -10, r: p.radius, d: p.density};
}
else
{
if(Math.sin(angle) > 0)
{
snow[i] = {x: -5, y: Math.random()*H, r: p.radius, d: p.density};
}
else
{
snow[i] = {x: W+5, y: Math.random()*H, r: p.radius, d: p.density};
}
}
}
}
}

window.onload = function(){
init();
setInterval(draw, 33);
}

window.addEventListener('resize', function(){
  sky.width = W = window.innerWidth;
  sky.height = H = window.innerHeight;
}, false);
* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
  background-color: rgba(0, 0, 0, 1);
}
<html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <canvas id="sky"></canvas>
    <script src="snow.js"></script>
  </body>
</html>

Can anyone identify why the particles are falling just once and offer some insights on resolving this issue? Appreciate your help.

Answer №1

This issue arises because the snow flakes are being reset to incorrect object properties when they exit the screen.

The original object (and all methods) expect attributes such as x, y, radius, and density.

However, during the object update process, you are using attributes like x, y, r, and d.

If you simply rename r and d to match the correct names, the solution should work effectively.

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

The loop for setState appears to only execute during the final iteration

My app revolves around friends and events, with each friend hosting specific events. I am trying to extract all the events from every friend in the system. To manage these events, I have declared an 'event' state variable as const [events, se ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

What is the best way to view an image before sending it to the server?

My form for adding products to the online store has several fields: Product Name Product Code Product Description Product Price Product Image I would like the user/admin to be able to select an image using ...

Maintain the button's color when clicked UNTIL it is clicked again

I am facing a challenge where I need to dynamically select multiple buttons that change color upon click. Once a button is clicked, it should change color and if clicked again, revert back to its original color. Unfortunately, I cannot rely on HTML attribu ...

Input text fields are restricted to only accept numerical values

I recently tried out the Jquery Numeric plugin, but unfortunately I discovered that it does not work on FireFox 3.6 on OSX as it does not allow pasting. Therefore, I am in search of a different Jquery plugin or Javascript snippet that specifically allows ...

Having trouble running the npm development server

The command npm run dev was executed. This ran the scripts concurrently using "npm run server" and "npm run client". Error from npm: Missing script: servernpm npm error. Did you mean this? Should it be: npm run server # to run the "server" package script ...

Trouble with jQuery UI add/remove class duration feature

I have implemented Jquery UI with the addClass/removeClass function successfully. However, I am facing an issue where the class changes without the specified duration. Below is the relevant code snippet: <script src="https://ajax.googleapis.com/ajax/li ...

Tips for avoiding the 'ResizeObserver loop finished with unhandled notifications.' error when using React with mui/material/Table

This is our current code snippet: import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableC ...

React Navigation functions properly during debugging but encounters issues in release mode

I've been encountering an issue for the past few weeks with my react-native app. I'm using react-navigation, and while everything works fine when testing on my device in debug mode, the navigation breaks after building a signed APK. I've tri ...

Having trouble with button functionality following the implementation of jquery.min.js?

We have implemented the code below, following the suggestion from this source, to replace text with icons. However, after applying the code, especially the Jquery.min.js file, the "add to cart" button on this page is no longer functioning. <script src= ...

The error message UnhandledPromiseRejectionWarning is triggered due to a TypeError stating that the function authenticate is

Currently, I am attempting to incorporate basic authentication into my API project using Knex, Express, and MySQL. Here are the functions I have implemented: const users = [{ id:1, username:'selia', password:'fullservice'}] functio ...

A guide on organizing dates in a datatable using the dd-MMM-yyyy hh:mm tt format

I have encountered an issue with sorting the date column in my datatable. Here is a screenshot showcasing the problem. Below is the code I am using: <table id="tbl" class="table table-small-font table-bordered table-striped"> <thead> &l ...

Tips for removing a DOM element in Selenium using Java

Recently, I've been attempting to remove an element from a website using Selenium and Java with the xpath of the element readily available. WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]")); The specific e ...

Which is better for AJAX file uploads: Multipart or base64 encoding?

I am currently developing a single page application using EmberJS and have come across the task of uploading multiple files. To address this, I created a custom view that encapsulates the file input field functionality, allowing me to link the selected fi ...

Include jQuery from a different directory

A Closer Look at the Symptoms Encountering issues with jQuery file paths can lead to undefined errors. With jQuery located in different directories, such as the root or child directory, certain JavaScript files may fail to recognize its presence. The sol ...

What is the best method for transforming JSON containing multiple objects into an array using JavaScript?

I have received a JSON response structured as follows. [ { "week":1, "win":10, "lose":[ { "week":2, "count":1 }, ...

What is the best way to arrange this by DateTransaction using a dropdown list?

Requesting assistance from the PHP community! I'm a newbie and in need of your expertise. My task is to create a dropdown list that sorts a table based on the DateTransaction column, with options ranging from January to December. Here is the code sni ...

After the initial jQuery request loads, the subsequent ajax request does not result in any updates to the Document Object Model

I have encountered an issue with two similar jQuery AJAX codes. Separately, each code works correctly. However, when I try to load the second code after loading the first, it does not update the DOM even though it appears to work (I have tested by adding d ...

Increase the thickness of the scrollbar track over the scrollbar thumb

I've come across several discussions on making the track thinner than the scrollbar thumb, but I'm looking to do the opposite. Is it possible to have a scrollbar track that is thicker than the scrollbar thumb? ...

What are the steps to adjust my table width without allowing horizontal scrolling?

1- I need help fixing the width of my table so that it stays within the screen. 2- Is there a way to display only the first 100 characters of table data and show the rest when clicked? Any assistance would be greatly appreciated. Here is a snippet from ...