Is there an opacity setting in javascript's p5 library?

Viewed 2389

I'm using the p5 library so functions like fill() rect() ellipse() but is there a way to change the opacity of a shape so even if I fill() it I can still see the shapes behind it?

3 Answers

You need to fill the shape with a transparent color. The fill() color can be specified in many different ways. For instance with the 3 color channels (red, green, blue) and the alpha channel.

e.g.: Red color 50% transparency

fill(255, 0, 0, 127);

Refer to the fill documentation for all of the different options.

I'm not certain if you're creating color variables, but using setAlpha could help to adjust the alpha value only as needed. If you just need to set the alpha when you set the color, Rabbid76's answer will do just fine.

Below is an example borrowed from the setAlpha reference page.

var squareColor;
function setup() {
  createCanvas(400, 400);
  // assign our color variable to change the alpha later
  squareColor = color(100, 50, 100);
}

function draw() {
  clear();
  background(200);
  // In the default RGB mode the transparency (alpha) value range is between 0 and 255
  squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
  fill(squareColor);
  rect(20, 20, 60, 60);
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.min.js"></script>

What you have to do is give the shapes a transparent color, so then you can see behind the shapes.

 background(220);
//   The color of the first Shape
// The first parameter is the redness, the second is the greenness, the third is the blueness, and the fourth parameter is called "Alpha" which determines the transparency
  fill(255,0,0,50);
//   The first Shape
  circle(200,200,200);
//   The color of the second Shape
  fill(0,255,0,50);
//   The second shape
  circle(200,200,150)
 

If what you're asking is just to see the outline of the shapes, you can simply draw the smaller shapes on the canvas AFTER you draw the larger shapes. Nonetheless, I would recommend reading this article.

Related