make gradient with p5.js
- User
make gradient with p5.js
- Assistant
In p5.js, you can create a gradient by smoothly interpolating between colors across a given shape. However, unlike some graphic software or CSS, p5.js doesn't have a built-in function for creating gradients. Instead, you will need to write a function that manually blends colors.
Here's an example of how you can make a two-color linear gradient in p5.js. This will create a vertical gradient rectangle that transitions from blue at the top to red at the bottom:
function setup() { createCanvas(400, 400); } function draw() { // Define colors let color1 = color(0, 0, 255); let color2 = color(255, 0, 0); // Call the gradient function setGradient(0, 0, width, height, color1, color2); noLoop(); // Ensure the gradient isn't redrawn every frame } function setGradient(x, y, w, h, c1, c2) { noFill(); // Don't fill the rectangle // For every y pixel in the rectangle for (let i = y; i <= y + h; i++) { let inter = map(i, y, y + h, 0, 1); // Calculate interpolation value let c = lerpColor(c1, c2, inter); // Interpolate between color1 and color2 stroke(c); // Set the color for the row line(x, i, x + w, i); // Draw a line with the interpolated color } }