为什么我的代码完全按照课程所讲的写的,但是那个固定的三角形图形显示不出来,只有黑色的背景色
html code:
js code:
var canvas = document.getElementById(‘myCanvas’)
//console.log(canvas.getContext(‘webgl’))
var gl = canvas.getContext(‘webgl’)
var program = gl.createProgram()
var VSHADER_SOURCE, FSHADER_SOURCE
VSHADER_SOURCE =
‘attribute vec4 a_Position;\n’ +
‘void main () {\n’ +
‘gl_Position = a_Position;\n’ +
’}\n’
FSHADER_SOURCE =
‘void main () {\n’ +
‘gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n’ +
’}\n’
var vertexShader, fragmentShader
function createShader (gl, sourceCode, type) {
// create shader
var shader = gl.createShader(type)
gl.shaderSource(shader, sourceCode)
gl.compileShader(shader)
return shader
}
// define vertex shader
vertexShader = createShader(gl, VSHADER_SOURCE, gl.VERTEX_SHADER)
// define frament shader
fragmentShader = createShader(gl, FSHADER_SOURCE, gl.FRAGMENT_SHADER)
console.log(vertexShader)
//attach shader to program
gl.attachShader(program,vertexShader)
gl.attachShader(program,fragmentShader)
//link program to context
gl.linkProgram(program)
gl.useProgram(program)
gl.program = program
function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.5, -0.5, -0.5, 0.5, -0.5
])
var n = 3
var vertexBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
// write data into the buffer object
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
// get attribute a_Position address in vertex shader
var a_Position = gl.getAttribLocation(gl.program, ‘a_Position’)
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
// enable a_Position variable
gl.enableVertexAttribArray(a_Position)
return n
}
//wirte the positions of vertices to a vertex shader
var n = initVertexBuffers(gl)
gl.clearColor(0, 0, 0, 1)
//clear canvas and add background color
function draw(){
gl.clear(gl.COLOR_BUFFER_BIT)
gl.drawArrays(gl.TRANGLES, 0, n)
console.log(‘1’)
}
draw()
登录后可查看更多问答,登录/注册
1.4k 16
1.0k 11
1.1k 11
4.8k 10
2.2k 9