WegGL ContextAttributes.alpha和Three.js WebGLRenderer构造器参数alpha的不同

159 阅读2分钟

WegGL ContextAttributes.alpha和Three.js WebGLRenderer构造器参数alpha的不同

three.js是使用了canvaswebgl context实现的。在创建WebGLRenderer时,会通过调用canvas.getContext()来获取webgl context。调用这个方法时,还可以传递一个对象,即ContextAttributes来配置一些行为。

我们这一次要讨论的内容,就是关于ContextAttributes.alpha的。

WebGLRenderer获取WebGL Context

WebGLRenderer的构造器中,可以找到下面的代码:

const contextAttributes = {
    alpha: true,
    depth: _depth,
    stencil: _stencil,
    antialias: _antialias,
    premultipliedAlpha: _premultipliedAlpha,
    preserveDrawingBuffer: _preserveDrawingBuffer,
    powerPreference: _powerPreference,
    failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
};

// ...

if (_gl === null) {

    const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];

    // ...

    _gl = getContext(contextNames, contextAttributes);

在获取context时,传入的contextAttributes.alpha的值固定为true,所以,WebGLRenderer构造器参数中的alpha,和这里不是一个东西。

ContextAttributes.alpha

我们可以通过WebGLspec文档,了解这个属性的作用。WebGL Specification (khronos.org)

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.

如果这个值为true,就会给渲染缓冲区添加alpha通道(透明度);如果这个值为false,则没有可以使用的alpha缓冲区。

我们可以做的试验验证一下:

  • 首先要明白当ContextAttributes.preserveDrawingBuffer为默认值false时,在创建好WebGL Context时,会给颜色缓冲区写入默认值rgba(0, 0, 0, 0)

  • 在创建WebGL Context时,如果alpha = true,则表示有alpha通道(缓冲),canvas的背景应该是透明的(自动写入rgba(0, 0, 0, 0)

  • 在创建WebGL Context时,如果alpha = false,这表示没有alpha通道(缓冲),canvas的背景应该是黑色的(自动写入rgba(0, 0, 0, 0),但是没有alpha通缓冲,丢弃了透明度,所以相当于写入了rgb(0, 0, 0))。

true

        const canvas = document.querySelector('#c')
        const gl = canvas.getContext('webgl', { alpha: true });

canvas绘制了一张透明的图片。

false

        const canvas = document.querySelector('#c')
        const gl = canvas.getContext('webgl', { alpha: false})

canvas绘制了一张不透明全黑色图片。

也可以gl.clearColor()设置清空颜色缓冲区时使用的颜色,然后调用gl.clear()清空颜色缓冲区。在alpha = false时,gl.clearColor()设置的alpha通道(最后一个参数),不会生效。

Three.js renderer constructor alpha param

上面已经提到过了,Three.js获取context时,alpha参数始终是true。在three.js创建WebGLRenderer时,设置alpha参数的作用:

 controls the default clear alpha value. When set to true, the value is 0. Otherwise it's 1. Default is false.

用来设置默认的clearAlpha

也可以从代码中找到对应的设置。

先通过getClearColor()找到这个值在background中存着:

this.getClearColor = function (target) {
    return target.copy(background.getClearColor());
};

接下来看一下background的初始化:

background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );

参数中的_alpha就是创建WebGLRenderer时传递进去的。然后看一下WebGLBackgroundd额构造器:

function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) {

    const clearColor = new Color(0x000000);
    let clearAlpha = alpha === true ? 0 : 1;
    //...
}