Gradient color in Line


#1

Hello! It’s me again :blush: with the beginner question.

So I was playing around with lines as you can see in the code below and I want to make the gradient color from black to white in the lines to give effect of depth. But I don’t know how to do it. I try to read the gradient function in the library but I couldn’t understand :frowning_face:

Gradient Lines

function setup() {
    createCanvas(600, 300);
}

function draw() {
    background(220);
    for (let y = 20; y <= height - 20; y += 20) {
        for (let x = 20; x <= width - 20; x += 20) {

            //draw lines
            stroke(50);
            line(x, y, mouseX, mouseY);

            //draw dot
            fill(220);
            noStroke();
            ellipse(x, y, 5, 5);

        }
    }
}

Any idea how to it? :relaxed:

Thanks


#2

Example:


void gradiant_line( color s, color e, float x, float y, float xx, float yy ) {
  for ( int i = 0; i < 100; i ++ ) {
    stroke( lerpColor( s, e, i/100.0) );
    line( ((100-i)*x + i*xx)/100.0, ((100-i)*y + i*yy)/100.0, 
      ((100-i-1)*x + (i+1)*xx)/100.0, ((100-i-1)*y + (i+1)*yy)/100.0 );
  }
}

float px, py;

void setup() {
  size(600, 600);
  px = 300;
  py = 300;
}

void draw() {
  background(128);
  gradiant_line( color(0), color(255), mouseX, mouseY, px, py );
}

This could probably be improved…


#3

@TfGuy44 is spot on however this is a question about p5 so the syntax is slightly different. Also took the liberty of changing some of the names.

function gradiantLine(color1, color2, x1, y1, x2, y2) {
  for (let i = 0; i < 100; i ++) {
    stroke(lerpColor(color1, color2, i/100.0));
    line(
      ((100 - i) * x1 + i * x2) / 100.0,
      ((100 - i) * y1 + i * y2) / 100.0, 
      ((100 - i - 1) * x1 + (i + 1) * x2) / 100.0, 
      ((100 - i - 1) * y1 + (i + 1) * y2) / 100.0
    );
  }
}

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

function draw() {
  background(128);
  gradiantLine(color(0), color(255), mouseX, mouseY, 300, 300);
}

#4

Awesome! It works very well. I think I am started to understand about the lerpColor function. Thank you for your guidance :star: