
The key is to separate the line into for example 30 segments. You draw each segment with increasing strokeWeight()
. The more segments you have, the smoother the line will look.
You can use lerp()
to find x,y coordinates for points between two ends.
You can use lerp()
to find strokeWeight()
for lines between two ends.
function setup() {
createCanvas(200, 200);
background("black");
stroke("white");
gradientLine(0, 0, 50, 50, 1, 3, 30);
noLoop();
}
function gradientLine(
start_x,
start_y,
end_x,
end_y,
start_weight,
end_weight,
segments
) {
let prev_loc_x = start_x;
let prev_loc_y = start_y;
for (let i = 1; i <= segments; i++) {
let cur_loc_x = lerp(start_x, end_x, i / segments);
let cur_loc_y = lerp(start_y, end_y, i / segments);
push();
strokeWeight(lerp(start_weight, end_weight, i / segments));
line(prev_loc_x, prev_loc_y, cur_loc_x, cur_loc_y);
pop();
prev_loc_x = cur_loc_x;
prev_loc_y = cur_loc_y;
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.0.0/lib/p5.min.js"></script>
EDIT:
Also, in case one is working with colours with alpha < 255
, such artifacts can appear:

This happens because the default capping for strokes is set to ROUND
. Setting strokeCap(SQUARE)
will fix this problem:

This needs to be set in the push()...pop()
block in gradientLine(...)
function. (Note: This will make the ends of the line look flat, and that needs more refined work.)