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.