Loizos Vasileiou
Loizos Vasileiou

Reputation: 704

Is it possible to make a transparent background color on javascript (p5js)?

Hello i was wondering if its possible to make the backround of a canvas looks transparent (no color). The code snippet below shows an example of what im trying to explain.. Please if you have any suggestions let me know

function setup() {
  createCanvas(400, 400);
}

function draw() {
  /* How to make a transparent color????? */
  background(220);
  rect(100,100,100,200);
}
html, body {
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.dom.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

Upvotes: 2

Views: 9751

Answers (4)

RFerreira
RFerreira

Reputation: 68

In your draw() function call the background function with the CSS property rgba and alpha=0:

function draw() {
   clear();
   background('rgba(255,255,255, 0)');
   ...
   ...
}

Upvotes: 0

Oscar Nguyen
Oscar Nguyen

Reputation: 53

It depends on your meaning of transparent.

If you want the transparent like displaying trail in your animation, add alpha. Under/

background(0, 50);

The '50' number is alpha. The '0' number is black.

Upvotes: 0

Kevin Workman
Kevin Workman

Reputation: 42176

It depends on exactly what you mean by transparent.

If you want it to be completely transparent, then you're probably looking for the clear() function. More info can be found in the reference, but to summarize: the clear() function acts like the background() function but makes everything transparent instead of any particular color.

If you want your background to be partially transparent, like a color that you can still see through, then you also need to add an alpha argument to your call to the background() function. Again, more info can be found in the reference, but here's an example:

function setup() {
  createCanvas(400, 400);
}

function draw() {
  clear();
  background(220, 10);
  rect(100, 100, 100, 200);
}

Note that you still need to call clear(), otherwise the transparent background is drawn on top of old scenes, which is probably not what you want.

Upvotes: 4

Loizos Vasileiou
Loizos Vasileiou

Reputation: 704

Another option I found is to not call the background() function:

var check = false;
function setup(){
  createCanvas(500,500);
}
function draw(){

  fill(random(255),random(255),random(255));
  rect(100,100,50,90);
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

Upvotes: 1

Related Questions