WebGL“绘制正方形”程序,需要帮助进行调试

时间:2018-08-31 16:34:10

标签: javascript html5 canvas webgl

我正在学习LearningWebGL教程,但我无法重现第一个代码本身。这是儿童车代码:

$dataProvider->pagination->pageSize = ($this->myPageSize !== NULL) ? $this->myPageSize : 10;`
var modelView = mat4.create()
var projection = mat4.create()
var vertexPositionPointer, modelViewMatrixPointer, projectionMatrixPointer
var vertexBuffer
var vertices =
[
  0.5, 0.5, 0.0,
  -0.5, 0.5, 0.0,
  0.5, -0.5, 0.0,
  -0.5, -0.5, 0.0
]

var vertexShaderSource =
"attribute vec3 vertexPosition;"+ "\n" +
"uniform mat4 modelView;"+ "\n" +
"uniform mat4 projection;"+ "\n" +

"void main(){"+ "\n" +
"gl_Position = projection * modelView * vec4(vertexPosition, 1.0);"+ "\n" +
"}";

var fragmentShaderSource =
"void main(){"+ "\n" +
"gl_FragColor = vec4(1.0, 0, 0, 1.0);"+ "\n" +
"}";

function setup(){
    var canvas = document.getElementById('canvas')
    var gl = canvas.getContext("webgl", {antialias : false})

    gl.viewport(0, 0, canvas.clientWidth, canvas.clientHeight)

    var vertexShader = getShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
    var fragmentShader = getShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)

    var program = gl.createProgram()
    gl.attachShader(program, vertexShader)
    gl.attachShader(program, fragmentShader)
    gl.linkProgram(program)
    gl.useProgram(program)

    vertexPositionPointer = gl.getAttribLocation(program, "vertexPosition")
    gl.enableVertexAttribArray(vertexPositionPointer)

    modelViewMatrixPointer = gl.getUniformLocation(program, "modelView")
    projectionMatrixPointer = gl.getUniformLocation(program, "projection")


    vertexBuffer = gl.createBuffer()
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)

    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
    gl.vertexAttribPointer(vertexPositionPointer, 3, gl.FLOAT, gl.FALSE, 0, 0)

    gl.clearColor(0, 0, 0, 1)
    gl.clear(gl.COLOR_BUFFER_BIT)

    mat4.translate(modelView, modelView, [0, 0, -1.4])
    mat4.perspective(projection, Math.PI/3.5, canvas.clientWidth/canvas.clientHeight, 1, 1000)

    gl.uniformMatrix4fv(modelViewMatrixPointer, false, modelView)
    gl.uniformMatrix4fv(projectionMatrixPointer, false, projection)
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
}

function getShader(gl, type, source){
    var shader = gl.createShader(type)
    gl.shaderSource(shader, source)
    gl.compileShader(shader)

    console.log(gl.getShaderParameter(shader, gl.COMPILE_STATUS))
    console.log(gl.getShaderInfoLog(shader))

    return shader;
}

setup()

上面的代码产生:

enter image description here

即使z-translate值设置为-1,整个画布也被涂成红色,这也是不正确的。

我做错了什么?.... (一些虚构的文本,使我的单词数增加,并且帖子通过了...)

0 个答案:

没有答案