wardrobefanatic
wardrobefanatic

Reputation: 101

How can I fill a shape with a gradient on p5.js?

First, I do know how to make gradients when it's formed within a square shape as its' a default shape when making manual gradients with for loops and lerpColor.

I am trying to create ideally any shape, in this case an ellipse that will have a linear gradient as a fill color. What I will do with this gradient is that I will have it animate across the page, so that it will create various shapes with the gradient.

I went to the p5.js example page to look for creating gradients, however I only managed to find gradients made manually using line(), stroke() and lerpColor. I looked around Processing forums and this Medium article though I don't have an understanding on Processing syntax.

Is there a way to tackle this?

Upvotes: 8

Views: 11536

Answers (1)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11267

Porting code from Processing to p5.js is very straightforward,- simply replace variable type (int,float,...) in declarations into Javascript generic type var, and everything will just work out-of-the-box. For example, radial gradient Processing code ported into P5.JS is :

var dim;

function setup() {
  createCanvas(640, 360);
  dim = width/2;
  background(0);
  colorMode(HSB, 360, 100, 100);
  noStroke();
  ellipseMode(RADIUS);
  frameRate(1);
}

function draw() {
  background(0);
  for (var x = 0; x <= width; x+=dim) {
    drawGradient(x, height/2);
  } 
}

function drawGradient(x, y) {
  var radius = dim/2;
  var h = random(0, 360);
  for (r = radius; r > 0; --r) {
    fill(h, 90, 90);
    ellipse(x, y, r, r);
    h = (h + 1) % 360;
  }
}

So, I will not dare to call it a "porting", it's a copy-paste operation by nature to 99.9% accuracy ! HTH !

Upvotes: 3

Related Questions