Я хочу повторить функцию бесконечной, но я не мог - PullRequest
0 голосов
/ 01 июня 2019

Я хочу сделать какой-то эффект для моего фона, поэтому я решил добавить несколько фигур, летающих вокруг, но я делаю только одну фигуру, я не могу выполнить цикл или что-то еще

Я пытался вызвать функцию более одного раза, но это не такпомощь

function animasyon(a) {
    window.onload=function(){

        var id = setInterval(anim,5);

        $('body').append('<div class=shape></div>');
        $('body').append('<div class=shape></div>');

        var kutu = document.getElementsByClassName("shape");
        var pos = 0;
        var x = window.innerWidth;
        var y = window.innerHeight;
        var borderSize = Math.floor(Math.random() * 3 ) + 1;
        var ySize = Math.floor(Math.random() * y ) + 1;
        var Size = Math.floor(Math.random() * 30 ) + 5;
        var yon = Math.floor(Math.random() *2)+1;
        var dolu = Math.floor(Math.random() *2)+1;
        if (ySize > 50) { ySize-=20; }


            function anim(){

                if (pos == x) {
                    clearInterval(id);          
                    document.getElementById("shape").remove();
                }else{
                    pos++;
                    kutu[a].style.position = "absolute";
                    kutu[a].style.border = "solid rgb(119,38,53) "+borderSize+"px";
                    kutu[a].style.left = pos+"px";
                    kutu[a].style.width = Size+"px";
                    kutu[a].style.height = Size+"px";

                    if (yon == 1) { ySize-=0.2; } else { ySize+=0.2; }
                    if (dolu==1) {kutu[a].style.background = "rgb(119,38,53)";}
                    if (kutu[a].offsetTop < 0 || kutu[a].offsetTop > y-30) {document.getElementById("shape").remove();}

                    kutu[a].style.top = ySize+"px";
                }
             }
    }

}

animasyon(0);

Ответы [ 2 ]

1 голос
/ 01 июня 2019

Попробуйте вызвать функцию anim таким образом

setInterval(function(){anim()},5);
0 голосов
/ 01 июня 2019

Ваша проблема в том, что вы присваиваете функции window.onload значение внутри анимации функции

window.onload содержит только 1 функцию. Если вы вызываете функцию анимации более одного раза, то последняя перезапишет первую.

Редактировать: вам необходимо отделить логику анимации от логики загрузки страницы. Это совершенно разные вещи.

Вот пример добавления нескольких объектов и анимации каждого по отдельности.

// HTML
<div id="container">
  <div id="ball"></div>
  <div id="ball2"></div>
  <div id="ball3"></div>
  <div id="ball4"></div>
</div>
// CSS
#ball, #ball2, #ball3, #ball4 {
  background: red;
  border: 1px solid #FAFDFA;
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 2em;
  position: absolute;
}

#ball2 {
  background: blue;
}

#ball3 {
  background: green;
}

#ball4 {
  background: purple;
}

#container {
  width: 512px;
  height: 512px;
  background: black;
  position: relative;
}
// JS
const container = document.getElementById('container');
const stageWidth = 512;
const stageHeight = 512;
const makeFall = (elementId) => {
    // this function makes an enlement fall in random direction
  const animationSpeed = 4;
  // your onload function
  const ball = document.getElementById(elementId);
  let directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
  let directionY = Math.random() * animationSpeed;
  const setRandomStart = () => {
    ball.style.top = '10px';
    ball.style.left = (Math.random() * (stageWidth / 2)) + 'px';
    directionX = (Math.random() * animationSpeed * 2) - animationSpeed;
    directionY = Math.random() * animationSpeed;
  }
  setRandomStart();
  let animationInterval = setInterval(() => {
    let px = parseFloat(ball.style.left);
    let py = parseFloat(ball.style.top);
    px += directionX;
    py += directionY;
    if (px > stageWidth - 20 || py > stageHeight    - 20 || px < -20) {
      setRandomStart();
    } else {
      ball.style.left = px + 'px';
      ball.style.top = py + 'px';
    }


  }, 48);
}

// In Your onload function you can add the elements and then animate


makeFall('ball');
makeFall('ball2');
makeFall('ball3');
makeFall('ball4');

https://jsfiddle.net/753oL8re/4/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...