WebGL 错误的 OpenGL 形状绘制顺序

WebGL wrong drawing order for the OpenGL shapes

我想使用 WebGL(用于浏览器的 OpenGL)测试一些东西,我编写了简单的 js 代码来绘制线和点。所以我有绘制多个形状的函数 draw(),首先它绘制多条线,然后绘制多个圆(表示为正方形)。但碰巧线条画在圆圈上方,就好像绘制顺序颠倒了一样。知道为什么吗??

drawShapes(gl.LINES, { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })
drawShapes(gl.POINTS, { r: 0.0, g: 1.0, b: 0.0, a: 1.0 })

下面是完整的源代码

let canvas = document.getElementById('canvas');
        let gl = canvas.getContext('webgl');

        let vertices = [
            -0.7, -0.1, 0,
            -0.3, 0.6, 0,
            -0.3, -0.3, 0,
            0.2, 0.6, 0,
            0.3, -0.3, 0,
            0.7, 0.6, 0
        ]

        function drawShapes(shape, color) {

            // Create an empty buffer object
            let vertex_buffer = gl.createBuffer()
            gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer)
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
            gl.bindBuffer(gl.ARRAY_BUFFER, null)

            // Vertex shader source code
            let vertCode = `
            attribute vec3 coordinates;
            void main(void) {
                gl_Position = vec4(coordinates, 1.0);
                gl_PointSize = 10.0;
            }`

            // Create a vertex shader object
            let vertShader = gl.createShader(gl.VERTEX_SHADER)
            gl.shaderSource(vertShader, vertCode)
            gl.compileShader(vertShader)
            let fragCode = `
            void main(void) { 
                gl_FragColor = vec4(${color.r}, ${color.g}, ${color.b}, ${color.a});
            }`

            let fragShader = gl.createShader(gl.FRAGMENT_SHADER)
            gl.shaderSource(fragShader, fragCode)
            gl.compileShader(fragShader)

            let shaderProgram = gl.createProgram()
            gl.attachShader(shaderProgram, vertShader)
            gl.attachShader(shaderProgram, fragShader)

            gl.linkProgram(shaderProgram)
            gl.useProgram(shaderProgram)
            gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer)

            // Get the attribute location
            let coord = gl.getAttribLocation(shaderProgram, "coordinates")
            gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0)
            gl.enableVertexAttribArray(coord)


            gl.enable(gl.DEPTH_TEST)
            gl.viewport(0, 0, canvas.width, canvas.height)
            gl.drawArrays(shape, 0, 6)
        }

        function draw(shape, color) {

            // change background color
            gl.clearColor(0, 0, 0, 0.7)
            gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

            drawShapes(gl.LINES, { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })
            drawShapes(gl.POINTS, { r: 0.0, g: 1.0, b: 0.0, a: 1.0 })
        }
        draw()
<!doctype html>
<html>

<body>
    <canvas width="500" height="500" id="canvas"></canvas>
</body>

</html>

您已启用深度测试。由于先绘制线条,因此它们首先进入深度缓冲区。在同一位置绘制点时,深度测试会阻止像素绘制在线的顶部。

            gl.enable(gl.DEPTH_TEST)

要么 a) 在点后画线。 b) 将深度函数设置为 GL_LEQUAL