Home > Software engineering >  Try to create rain fall in JS
Try to create rain fall in JS

Time:08-24

I learn javascript and i try to create a rain falling in js but have a problem. After many tries i code something like this. First version of my app can simulate to rain for only one rain drop and now i'd like to translate it to many of rain drops

function Raining() {
  setInterval(Raining, 40)
  if (yPosition < 1000) {
    yPosition  = step
  } else {
    yPosition = 0
    rain.style.top = 0
  }
}

//Rain
let xPosition;
let yPosition = 0;
const step = .5


//Making water
for (i = 0; i < 20; i  ) {

  const el = document.createElement('div')
  document.querySelector('body').appendChild(el)
  //Random x location
  let randomXPosition = Math.trunc(Math.random() * 100   1)
  el.style.left = `${randomXPosition}%`
}
let rain = document.querySelectorAll('div')
for (i = 0; i < rain.length; i  ) {
  rain[i].style.top = `${yPosition}px`
  Raining()
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  overflow: hidden;
  height: 100vh;
}

div {
  position: absolute;
  top: 0;
  left: 50%;
  background-color: royalblue;
  width: 3px;
  height: 20px;
}
<div ></div>

Code execute only once . I know that here is a lot of mistakes but please help what's wrong here.

CodePudding user response:

You have more than one rain

This works better but you really ned a random step for each drop

function Raining() {
  yPosition  = step;

  for (i = 0; i < rain.length; i  ) {
    yPosition  = Math.floor(Math.random()*i)
    rain[i].style.top = `${yPosition}px`
  }
  if (yPosition > 1000) {
    yPosition = 0
  }
}

//Rain
let xPosition;
let yPosition = 0;
const step = .5

//Making water
for (i = 0; i < 20; i  ) {
  const el = document.createElement('div')
  document.querySelector('body').appendChild(el)
  //Random x location
  let randomXPosition = Math.trunc(Math.random() * 100   1)
  el.style.left = `${randomXPosition}%`
}
let rain = document.querySelectorAll('div')

setInterval(Raining, 300)
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  overflow: hidden;
  height: 100vh;
}

div {
  position: absolute;
  top: 0;
  left: 50%;
  background-color: royalblue;
  width: 3px;
  height: 20px;
}
<div ></div>

  • Related