juliangarnier / anime

JavaScript animation engine
https://animejs.com
MIT License
49.63k stars 3.67k forks source link

Canvas animation flickering #655

Open garyanikin opened 4 years ago

garyanikin commented 4 years ago

Describe the bug A trying to implement animation on canvas. There is background with triangle pattern and appearing squares. Sometimes there is flickering in squares animation. I dont undestand why it happens, I think I make an error in animation lifycicle. It's my second project on animejs

To Reproduce Steps to reproduce the behavior:

  1. Go to https://animejs-triangles-flickering.surge.sh
  2. Just wait a couple of second, you will see triangle shapes appearing and sometimes flickering

Expected behavior Smooth animation of fade in and fade out triangle shapes

Additional context This is github repo with code: https://github.com/garyanikin/animejs-trinagles-animation

This are the main methods for animation: setting render

var render = anime({
      duration: Infinity,
      update: function() {
        resetCanvas(canvas);
      }
    });

 function resetCanvas(canvas) {
    const ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBackground(canvas);
  }

create squares to animate

function createSquare(ctx, x, y) {
    var p = {};
    p.x = x;
    p.y = y;
    p.alpha = 0;
    p.draw = function() {
      ctx.globalAlpha = p.alpha;
      ctx.fillRect(p.x, p.y, square_size, square_size);
      ctx.globalAlpha = 1;
    };
    return p;
  }

animation

const easing = "easeInOutQuad";
    const duration = anime.random(300, 600);
    const closest_duration = anime.random(300, 600);
    const update = anim => {
      anim.animatables.map(({ target }) => target.draw());
    };

    anime
      .timeline({
        easing
      })
      .add({ // show base squares
        targets: base,
        update,
        alpha: 1,
        duration
      })
      .add( // show closest squares
        {
          targets: closest,
          update,
          alpha: 1,
          duration: closest_duration
        },
        "+=" + closest_duration / 2
      )
      .add({ // hold
        alpha: 1,
        easing: "linear",
        targets: [...base, ...closest],
        update,
        duration: hold_duration
      })
      .add({ // hide all squares
        alpha: 0,
        easing,
        targets: [...base, ...closest],
        update,
        duration
      });

Guys please help me out to fix this flickering 🙏

garyanikin commented 4 years ago

My theory that render method with background drawning not synced with squares animation