2

Есть canvas с кругами. Проблемы в том, что круги мерцают(это из-за удаления объекта из массива), я вроде бы удаляю тот элемент, который надо и на секунду удаляется еще один элемент, и потом сразу же возвращается в массив, и получается эффект мерцания. Так же, когда круг находится рядом с мышью должен менять цвет на синий(в настройках указан как color2), но он почему-то меняется на белый.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body style="margin: 0;">
  <canvas id="canv" style="position: absolute;"></canvas>
  <script>
    var canv = document.getElementById("canv"),
      ctx = canv.getContext("2d"),
      w = canv.width = window.innerWidth,
      h = canv.height = window.innerHeight,
      log = val => console.log(val)
    var und;

    function getDist(x1, y1, x2, y2) {
      return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
    }

    function makeCircleObj(bool) {
      var rand = opts.radiusRand * Math.random();
      var radius = 'opts.radius sign rand'.replace('opts.radius', opts.radius).replace('rand', rand);
      radius = radius.replace('sign', Math.random() < .5 ? '+' : '-')
      radius = eval(radius)
      rand = opts.speedRand * Math.random();
      var speed = 'opts.speed sign rand'.replace('opts.speed', opts.speed).replace('rand', rand);
      speed = speed.replace('sign', Math.random() < .5 ? '+' : '-')

      var y;
      if (bool) y = 0 - radius;
      else y = Math.random() * h - radius / 2;

      return {
        radius: radius,
        speed: eval(speed),
        catched: false,
        addRadius: 0,
        x: Math.random() * w - radius / 2,
        y: y
      }
    }

    var opts = {
      radius: 25,
      radiusRand: 12,
      amount: 25,
      maxAmount: 45,
      speed: 1.25,
      speedRand: .25,
      kvRange: 150,
      radiusAdd: 15,
      color: 'rgba(255, 51, 153, .5)',
      color2: 'rgba(51, 255, 245, .5)'
    }

    var mouse = {};
    canv.onmousemove = e => {
      mouse.x = e.x;
      mouse.y = e.y;
    }

    var circles = new Array(opts.amount).fill().map(() => {
      return makeCircleObj()
    })

    function anim() {
      ctx.clearRect(0, 0, w, h)
      if (Math.random() < .145 && circles.length < opts.maxAmount) circles.push(makeCircleObj(true))

      circles.forEach((cur, i) => {
        if (
          cur.x > mouse.x - opts.kvRange && cur.x < mouse.x + opts.kvRange &&
          cur.y > mouse.y - opts.kvRange && cur.y < mouse.y + opts.kvRange
        ) {
          cur.catched = true;
          ctx.fillStyle = opts.color2
        } else {
          cur.catched = false;
          ctx.fillStyle = opts.color
        }

        cur.speed *= 1.002
        cur.y += cur.speed
        ctx.beginPath()
        if (cur.catched) 
          ctx.arc(cur.x, cur.y, cur.radius + cur.radiusAdd, 0, Math.PI * 2)
        else 
          ctx.arc(cur.x, cur.y, cur.radius, 0, Math.PI * 2)
        ctx.closePath()
        ctx.fill()
        if (cur.y > h + cur.radius) circles.splice(i, 1)
      })

      window.requestAnimationFrame(anim)
    }
    anim()
  </script>
</body>

</html>

1 ответ 1

2

Вы удаляете элементы из массива во время прохождения по нему методом forEach. Не надо.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body style="margin: 0;">
  <canvas id="canv" style="position: absolute;"></canvas>
  <script>
    var canv = document.getElementById("canv"),
      ctx = canv.getContext("2d"),
      w = canv.width = window.innerWidth,
      h = canv.height = window.innerHeight,
      log = val => console.log(val)
    var und;

    function getDist(x1, y1, x2, y2) {
      return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
    }

    function makeCircleObj(bool) {
      var rand = opts.radiusRand * Math.random();
      var radius = 'opts.radius sign rand'.replace('opts.radius', opts.radius).replace('rand', rand);
      radius = radius.replace('sign', Math.random() < .5 ? '+' : '-')
      radius = eval(radius)
      rand = opts.speedRand * Math.random();
      var speed = 'opts.speed sign rand'.replace('opts.speed', opts.speed).replace('rand', rand);
      speed = speed.replace('sign', Math.random() < .5 ? '+' : '-')

      var y;
      if (bool) y = 0 - radius;
      else y = Math.random() * h - radius / 2;

      return {
        radius: radius,
        speed: eval(speed),
        catched: false,
        addRadius: 0,
        x: Math.random() * w - radius / 2,
        y: y
      }
    }

    var opts = {
      radius: 25,
      radiusRand: 12,
      amount: 25,
      maxAmount: 45,
      speed: 1.25,
      speedRand: .25,
      kvRange: 50,
      radiusAdd: 15,
      color: 'rgba(255, 51, 153, .5)',
      color2: 'rgba(51, 255, 245, .5)'
    }

    var mouse = {};
    canv.onmousemove = e => {
      mouse.x = e.x;
      mouse.y = e.y;
    }

    var circles = new Array(opts.amount).fill().map(() => {
      return makeCircleObj()
    })

    function anim() {
      ctx.clearRect(0, 0, w, h)
      if (Math.random() < .145 && circles.length < opts.maxAmount) circles.push(makeCircleObj(true))

      //circles.forEach((cur, i) => {
      for(let i = 0; i < circles.length; i++) {
        let cur = circles[i];
        if (
          cur.x > mouse.x - opts.kvRange && cur.x < mouse.x + opts.kvRange &&
          cur.y > mouse.y - opts.kvRange && cur.y < mouse.y + opts.kvRange
        ) {
          cur.catched = true;
          ctx.fillStyle = opts.color2
        } else {
          cur.catched = false;
          ctx.fillStyle = opts.color
        }

        cur.speed *= 1.002
        cur.y += cur.speed
        ctx.beginPath()
        if (cur.catched) 
          ctx.arc(cur.x, cur.y, cur.radius + cur.addRadius, 0, Math.PI * 2)
        else 
          ctx.arc(cur.x, cur.y, cur.radius, 0, Math.PI * 2)
        ctx.closePath()
        ctx.fill()
        if (cur.y > h + cur.radius) {
          circles.splice(i, 1);
          i--;
        }
      }  
      //})

      window.requestAnimationFrame(anim)
    }
    anim()
  </script>
</body>

</html>

8
  • тоже пропадают .... 19 окт 2018 в 16:21
  • @НикитаФаст В смысле? Мерцания нет.
    – user176262
    19 окт 2018 в 16:22
  • Игорь я не спорю но там как бы сказано что они должны быть синими при наведении а они пропадают вообще но мерцания нету на самом деле 19 окт 2018 в 16:22
  • @НикитаФаст а, да. Не дочитал.
    – user176262
    19 окт 2018 в 16:23
  • 1
    Да по строке i-- понял, что элемент удаляется, массив сдвигается и следующий элемент как бы выпадает 19 окт 2018 в 16:32

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.