Horizontal gradient for line

Hi,
I have been trying out different ways to display horizontal gradients within lines, for example, do gradient for each circle and then put into lines. But it did not work.

I just wonder if the effect is possible to do in p5.js, or anyone is willing to help will be great! Thanks.

Here is the effect I try to achieve

Code:

function setup() {
  createCanvas(800, 500);
  noStroke()
  c1 = color(204, 102, 0);
  c2 = color(0, 102, 153);
  noLoop();
}

function draw() {
  background(220);
  gradientLine(50, 50, mouseX, mouseY, c1,c2, 60)
}

// gradient for line
function gradientLine(x1, y1, x2, y2, c1, c2, sz) {
  const d = dist(x1, y1, x2, y2)
  for (let i = 0; i < d; i++) {
    const step = map(i, 0, d, 0, 1)
    const x = lerp(x1, x2, step)
    const y = lerp(y1, y2, step)
    const c = lerpColor(c1,c2,step)
    console.log(c);
    fill(c)
    ellipse(x, y, sz, sz)
  }
}

// gradient for ellipse
function gradient(x1, y1, x2, y2, col1, col2) {
  var grad = drawingContext.createLinearGradient(x1, y1, x2, y2);
  grad.addColorStop(0, col1);
  grad.addColorStop(1, col2);
}

Hello @bringmeflowers,

This topic (Java version) may be of interest:

I was able to achieve this with a few modifications:

image

:)

Thank you so much! This is really helpful :grin:

1 Like