Home > Software design >  How to prevent compositing with an HTML canvas?
How to prevent compositing with an HTML canvas?

Time:04-28

I am developing an application using a WebGL canvas, and I notice through benchmarking that a significant amount of time is spent "compositing layers".

But I don't think this should be occurring, because my entire HTML page only has a single element (the canvas).

What I think is happening is that it's blending the background color of the HTML page with the contents that are drawn to the canvas. This seems to be the case since when I change the background color of my HTML page, elements in my scene drawn onto the canvas appear lighter or darker.

Is there a way to disable this compositing? I do not want to blend the background color of my page with what is drawn to the canvas. In doing so I hope not only will the entire "compositing" operation be removed (and performance saved), but also the contents of my canvas will no longer be blended with my page's background.

const canvas = document.querySelector("canvas");
const gl = canvas.getContext("webgl2");

gl.clearColor(0.25, 0.25, 0.25, 1);

function render() {
  gl.clear(gl.COLOR_BUFFER_BIT);

  requestAnimationFrame(render);
}

requestAnimationFrame(render);
<canvas></canvas>

Here's an example above. If you run this code and profile it, you'll notice a significant "Composite Layers" section in the results:

enter image description here

But I do not wish to composite with the background. Rather than blending with it, I want it to simply be pasted on top. Is there any way to remove this costly process?

CodePudding user response:

When you create the WebGL context, if you don't explicitly request the context to not have alpha, you get alpha, and the compositor will have to at least examine each pixel to determine if it needs blending with the page.

From section 5.2.1 of the WebGL standard:

alpha

If the value is true, the drawing buffer has an alpha channel for the purposes of performing OpenGL destination alpha operations and compositing with the page. If the value is false, no alpha buffer is available.

Try creating the context with "alpha:false":

const gl = canvas.getContext("webgl2",  { alpha: false } );
  • Related