1

How to effectively create curveVertex with an array of p5.Vector points which fades (decreases opacity) the trail after the mouse position?

So far the following code removes the trailing points after a certain amount of time, creating the effect of trailing after the mouse, but it does not create a translucent trail. The trailing stroke just goes away.

const trail = sk => {

  let points = [];
  let fadeTime = 1000;

  sk.setup = () => {
    sk.createCanvas(300, 600);
    sk.noFill();
  };

  sk.draw = () => {
    sk.clear();
    sk.beginShape();

    for (let i = points.length - 1; i >= 0; i--) {
      let p = points[i];
      let timeAlive = sk.millis() - p.z;

      if (timeAlive > fadeTime) {
        // start removing last point
        points.shift();
      } else {
        sk.strokeWeight(10);
        sk.strokeJoin(sk.ROUND);
        sk.strokeCap(sk.ROUND);
        sk.stroke(255, 255, 255);
        sk.curveVertex(p.x, p.y);
      }
    }
    sk.endShape();
  }

  // Add more points forward when dragging mouse
  sk.touchMoved = () => {
    points.push(sk.createVector(sk.mouseX, sk.mouseY, sk.millis()));
    return false;
  }
};

let mySketch = new p5(trail, elementId);
Pandemonium
  • 7,724
  • 3
  • 32
  • 51

1 Answers1

1

The problem is that shapes created using the beginShape() and vertex functions (including curveVertex()) can only have a single stroke and fill color. So you can't color parts of the shape differently from the rest of the shape.

To prove this, try changing this line:

sk.stroke(255, 255, 255);

To this line:

sk.stroke(random(256));

To get around this, you could make each section of your curve its own shape with its own color. Start by just making each section a random color.

Then you need to base the color of each section off of the current index. I recommend drawing out a few examples. If a curve has 10 sections, what color should section 1 have? Section 2? Section 10? Repeat that process until you notice a pattern.

If you get stuck, please post an updated MCVE in a new question, and we'll go from there. Good luck.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • I kind of get your point, but some how this solution will still result in a trail with several segments with various stroke colors since there is still a certain gap between each two points that a stroke connects. – Pandemonium Mar 29 '18 at 01:10
  • @Pie'Oh'Pah I'm not sure I understand what you're saying. Isn't that exactly what you want? – Kevin Workman Mar 29 '18 at 01:19