How to fill a shape with a gradient on p5.js?

Member

by denis , in category: Javascript , 2 months ago

How to fill a shape with a gradient on p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 2 months ago

@denis 

To fill a shape with a gradient on p5.js, you can use the beginGradientFill() method to define the gradient and then use the noStroke() and shape() functions to create the shape.


Here's an example code snippet that shows how to fill a shape with a gradient:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function setup() {
  createCanvas(400, 400);
  
  let gradient = drawingContext.createLinearGradient(0, 0, 0, height);
  gradient.addColorStop(0, 'red');
  gradient.addColorStop(1, 'blue');
  
  noStroke();
  fill(gradient);
  
  beginShape();
  vertex(100, 100);
  vertex(200, 100);
  vertex(200, 200);
  vertex(100, 200);
  endShape(CLOSE);
}


In this example, we first create a linear gradient using the createLinearGradient() method, specifying the starting and ending points of the gradient. We then add color stops to define the colors at different positions along the gradient.


Next, we use the noStroke() function to remove the outline of the shape, and the fill() function to set the fill color to the gradient we defined.


Finally, we use the beginShape() and endShape(CLOSE) functions to create a shape with the specified vertices. The shape will be filled with the gradient that we defined.