How can I make backgrounds in p5.js transparent bu

2019-07-31 17:00发布

I'm asking this as a follow-up to this question. I want to create a drawing app where the mouse is replaced by an ellipse that resizes to fit the brush size. The problem was that there was no way to draw the ellipse without leaving a mark on the canvas. The solution I came up with to solve this problem was to use createGraphics() as a buffer object and render the cursor on top of it as such:

var brushSize = 60;

function setup() {
  createCanvas(1080,720);
  pg = createGraphics(1080, 720);
  background(100);
  noCursor();
}


function draw() {
  pg.background(0,0,0,0);
  pg.fill(255);
  pg.noStroke();
  pg.ellipse(mouseX/2,mouseY/2,brushSize);
  image(pg, 0, 0);

}

function mouseDragged() {
  noStroke();
  fill(255); 
  ellipse(mouseX,mouseY,brushSize);

}

In my solution, I'm using createGraphics() to span over the entire canvas, rendering its own background and then drawing an ellipse at the cursor location. In p5.js, background() takes a fourth parameter that describes its alpha channel. I thought this would give me my desired effect and create a transparent background on the buffer which allows full visibility of the canvas without actually drawing to it. However, if I set the fourth parameter in pg.background() to 0, the Graphics background doesn't render over the Graphics ellipse, which means the transparency is only relative to objects in the Graphics buffer.

I need some help in figuring out if there is any way to make the Graphics buffer transparent to the canvas and not to objects that render on the Graphics buffer itself. I know this explanation might be a little confusing so I drew up a little diagram to show what I mean: enter image description here

1条回答
地球回转人心会变
2楼-- · 2019-07-31 17:42

It sounds like you're just looking for the clear() function. The clear() function makes a graphics object completely transparent. Use the pg.clear() function instead of the pg.background() function. You can find more info in the reference.

But also note that what I meant in my previous answer was that you could use the createGraphics() function to draw your painting to the buffer, and then draw the ellipse over top of that. Something like this:

function draw(){
  background(0);
  image(paintBuffer, 0, 0);
  ellipse(mouseX, mouseY, brushSize);
}

function mouseDragged(){
  paintBuffer.ellipse(mouseX, mouseY, brushSize);
}
查看更多
登录 后发表回答