How to draw a fading object trail? Without background manipulation

Viewed 278

I have a simple ellipse, moving across the screen, is there any simple code I could implement to have this ellipse draw a trail behind it that has its alpha fade over time to a certain extent? I still want the trail visible in the end but less bright than the casting ellipse.

2 Answers

Assuming the ellipse is the only thing being drawn then there is a simple solution which is to, instead of drawing a fully opaque background on each frame, draw a semi-transparent background:

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

function draw() {
  background(0, 35);
  ellipse(mouseX, mouseY, 20, 20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

However, there are some caveats, namely that for certain colors/transparency levels you will be left with permanent "ghost" of the trails due to some weird alpha blending math anomalies.

You could also do something like this:

let positions = [];

function draw(){
   positions.push(mouseX);
   positions.push(mouseY);

   for(let i in positions){
      let x = positions[i];
      let y = positions[i + 1];
      fill(255, 255 - i * 10); noStroke();
      ellipse(mouseX, mouseY, x, y)
   }

   if(positions.length > 20){
      positions.shift();
      positions.shift();
   }
}
Related