Make line shape fade away after x seconds

whats the best way to fade a line out?

I have this here: https://codepen.io/itsMeAra/pen/e6ebe0dec2d370f50217809c547052e7

Trying to figure out how to make the line fade away after .5 seconds to make sort of a trailing effect instead of having the line permanently drawn the way it is.

1 Like

if the line is an image, you can use tint(), it works pretty easily in a for loop.

for reference
https://p5js.org/reference/#/p5/tint

Hi,

Welcome to the community! :wink:

In order to make that trailing effect, you need to save all the positions of the line segments in order to draw them based on if they are at the beginning or at the end of the line.

To save data, you are going to need an array. At each frame, you will add the current mouse position into that array. Then when the array size is exceeding a certain value (a length), you pop the first item.

Check this example :

let points = [];
let maxLineLength = 50;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  // Add the current mouse position to the array
  points.push(createVector(mouseX, mouseY));
  
  // If the size of the line is too high
  if(points.length > maxLineLength){
    // Remove the first element from the list
    points.shift();
  }
  
  // Draw the line (a line between each points)
  for(let i=0; i<points.length - 1; i++){
    let p1 = points[i], p2 = points[i+1];
    // Interpolate the alpha value based on the position of the segment
    // To fade the line
    stroke(0, map(i, 0, points.length - 1, 0, 255));
    line(p1.x, p1.y, p2.x, p2.y);
  }
}

4 Likes

Ahhh, perfect. Thanks so much Joseph! Appreciate the help and detailed explanation.

1 Like

tint() becomes pretty expensive …

here is a great tut on the topic.