Canvas objects are not transparent to underlying HTML/CSS objects

The body of my html file has a gradient image as it’s background in addition to some other html. I am trying to use the canvas to create an overlay of interactive objects on top of all of the static html/css images beneath it. I have successfully made the canvas background completely transparent by simply setting the background to a transparent p5.color. After I got that working, I drew a couple of test rectangles on top to check that they would be translucent as well. This is where I run into the issue. I tried to change the two rectangles’ opacities using fill(255, 10); and fill(0, 10); respectively. They do become transparent to each other and correctly blend together. However, the gradient image from the html body is not visible beneath them. Instead, the rectangles appear to be solid against the gradient.

And here is a screenshot displaying how the rectangles are seemingly opaque:

And finally, the js code that I’m using:

// declare variables
var bg;

function setup() {

	// create canvas as the size of the window.
	// render it as a transparent black plane
	var cnv = createCanvas(windowWidth, windowHeight);
	cnv.parent('canvasdiv');
	frameRate(30);

	// colors
	bg = color(0, 0, 0, 0);

	// set background
	background(bg);

}


function draw() {

	// set the background color 
	background(bg);
	fill(255);
	// rect(400, windowHeight / 2, 10, 20);

	// testing the position of the canvas to make sure it's right 
	strokeWeight(10);
	point(0, 0);
	point(width, height);

	// test shapes 
	
	fill(255, 10);
	noStroke();

	rect(width/2, height/2, 200, 200);
	fill(0, 10);
	rect(width/2 + 50, height/2 + 50, 200, 200);


}

function windowResized() {
	resizeCanvas(windowWidth, windowHeight);
}

Instead of using a transparent background you need to use the clear() function. The issue is that your transparent background basically doesn’t do anything and leaves the shapes you’ve drawn in previous frames as is, so by repeatedly drawing the shapes, even with low opacity, they become more and more opaque very quickly. If you change the frame rate to 1 (i.e. frameRate(1) in setup), you will see what is happening clearly.

2 Likes