1

    <style>
      body { margin: 0; }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>
    <script>
    function setup(){
        createCanvas(500,200);
        s = createSlider(0,255,12);
        s.position(10,20);
    }
    let alphaVal = 0;
    function draw(){
        alphaVal = s.value();
        background(0,alphaVal);
        fill(255);
        circle(mouseX,mouseY,20);
    }
    </script>

Why low alpha values cause trails behind? Does p5 keeps track of all the things drawn since the previously drawn circles can be seen when background has transparency? Does that affect performance?

Rahul Gill
  • 23
  • 1
  • 7
  • You have to actively clear the background if you don't want this. "Does p5 keeps track of all the things drawn since the previously" not really, but the pixels remain in the canvas until they are overwritten –  May 28 '21 at 07:59
  • Note that with certain alpha values (like the one you did set), you can't come back to a pure black color (color values are integer so 255 * 0.95 -> 242 | * 0.95 -> 230 | ... -> 10 | * 0.95 -> 9 | * 0.95 -> 9 | * 0.95 -> 9 ...). And so you'll always have a [9,9,9] pixel ghost. – Kaiido May 28 '21 at 08:13

1 Answers1

1

To summarize, the draw() function will be called on every frame, so if the background has an alpha, it will draw a semi-transparent black rectangle on top of the previously drawn frame. This is why we can see the previous positions.

This doesn't impact the performance since this is how p5js is built. It will generate an image on every frame, then redraw on top of it on the next frame.

I hope it makes sense!

Miionu
  • 46
  • 5
  • 1
    It might also be worth noting that the way to get rid of this effect is to clear the canvas between each draw, https://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing – Karl-Johan Sjögren May 28 '21 at 07:58
  • @Karl-JohanSjögren the question is about the p5.js environment. To clear the canvas there, you'd call [clear()](https://p5js.org/reference/#/p5/clear) – Kaiido May 28 '21 at 08:15
  • Ah, well then that could be included instead. I just felt that while this answers the question a note about how to avoid the effect would make the answer even better. – Karl-Johan Sjögren May 28 '21 at 09:24