Gradients on p5.js?

Gradients are a pretty standard feature of HTML5 canvas:

And using straight javascript (actually this example is typescript)/canvas I can create a gradient line like this:

export class GradientLine extends DrawableObject {

	cp1: ColorPoint; 
	cp2: ColorPoint;
	size: number; 

	constructor(cp1 : ColorPoint, cp2 : ColorPoint, size = 1) {
		this.cp1 = cp1;
		this.cp2= cp2;

		this.size = size;

	draw(context : CanvasRenderingContext2D){

		let p1 = adjustPosition(context, this.cp1.position);
		let p2 = adjustPosition(context, this.cp2.position);

		var gradient = context.createLinearGradient(p1.x,p1.y,p2.x,p2.y);

		gradient.addColorStop(0, this.cp1.color.toString());
		gradient.addColorStop(1, this.cp2.color.toString());

		context.strokeStyle = gradient;
		context.lineWidth = this.size;

		context.moveTo(p1.x, p1.y);
		context.lineTo(p2.x, p2.y);



I’ve looked and the only thing similar is lerpColor - (example here)but that would, in the instance that I’m doing, require me to write a function that presumably draws an individual point for every point along the line.

Am I right in understanding this? Or is there a way to apply a generic gradient?

1 Like

Yeah pretty much the simplest way to get a gradient is lerpColor(). There’s no built in function for creating gradients but there’s plenty of examples on how to write a function that does it.

Also check out rotate() as it makes diagonal gradients easier to create.

1 Like

In addition to linear and radiant examples

…you might be interested in per-vertex coloring:

Here’s my solution for doing gradient lines. Pretty simple:

1 Like