WebGL基础学习

WebGL工作原理

step1:create vertexData
step2:create buffer and load vertexData to buffer

const buffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buffer) 
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertexData), gl.STATIC_DRAW)

step3: create vertex shader and fragment shader, create a program and attach shaders to the program

const vertexShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertexShader, `
attribute vec3 position;
void main() {
  gl_Position = vec4(position, 1);
}
`)
// compiles a GLSL shader into binary data so that it can be used by a  WebGLProgram.
gl.compileShader(vertexShader)

const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragmentShader,`
void main() {
  gl_FragColor = vec4(1, 0, 0, 1);
}
`)
gl.compileShader(fragmentShader)

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

step4:enable vertex attributes

//returns the location of an attribute variable in a given WebGLProgram ( get the index )
const positionLocation = gl.getAttribLocation(program, `position`)
//turns on the generic vertex attribute array at the specified index into the list of attribute arrays.
gl.enableVertexAttribArray(positionLocation) // positionLocation is a index present position attribute.
//binds the buffer currently bound to gl.ARRAY_BUFFER to a generic vertex attribute of the current vertex buffer object and specifies its layout.
gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 0, 0)

step5:draw

gl.useProgram(program)
gl.drawArrays(gl.TRIANGLES, 0, 3)

你可能感兴趣的:(WebGL基础学习)