javascriptp5.js

Flashing and flickering in p5js


I have the following code for a p5js project where I draw 10 eccentric squares and set the blend mode to DIFFERENCE. But the screen starts aggressively flashing and flickering.

let size = 50;
let c = ["red", "green", "blue"];

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  translate(width / 2, height / 2);

  push();
  blendMode(DIFFERENCE);
  for (let i = 10; i > 0; i--) {
    fill(c[i % 3]);
    rect(0 - (i * size) / 2, 0 - (i * size) / 2, size * i, size * i);
  }
  pop();
}

I tried adding push() and pop() but it doesn't seem to make a difference.

Why is it happening and how do i stop it? Also, is push() and pop() doing anything in this example?


Solution

  • You're not clearing the display between your draw calls, so you're differenceing over the last frame too.

    Adding a clear() fixes that.

    blendMode isn't in the list of attributes saved by push, so in this case push() and pop() do nothing.

    In the example below, I moved push() and pop() inside the loop, so they affect the translate() state, giving us a bit of a jiggle.

    let size = 50;
    let c = ["red", "green", "blue"];
    
    function setup() {
      createCanvas(windowWidth, windowHeight);
    }
    
    function draw() {
      let t = millis() / 400;
      translate(width / 2, height / 2);
      clear();
    
      blendMode(DIFFERENCE);
      for (let i = 10; i > 0; i--) {
        push();
        translate(Math.cos(i * t) * 20, Math.sin(i * t) * 20);
        fill(c[i % 3]);
        rect(0 - (i * size) / 2, 0 - (i * size) / 2, size * i, size * i);
        pop();
      }
    }
    <script src="https://cdn.jsdelivr.net/npm/p5@1.9.4/lib/p5.js"></script>