/*============ Creating a canvas =================*/varcanvas=document.getElementById("my_Canvas");gl=canvas.getContext("experimental-webgl");/*========== Defining and storing the geometry =========*/varvertices=[-0.5,0.5,0.0,-0.5,-0.5,0.0,0.5,-0.5,0.0,0.5,0.5,0.0];indices=[3,2,1,3,1,0];// Create an empty buffer object to store vertex buffervarvertex_buffer=gl.createBuffer();// Bind appropriate array buffer to itgl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer);// Pass the vertex data to the buffergl.bufferData(gl.ARRAY_BUFFER,newFloat32Array(vertices),gl.STATIC_DRAW);// Unbind the buffergl.bindBuffer(gl.ARRAY_BUFFER,null);// Create an empty buffer object to store Index buffervarIndex_Buffer=gl.createBuffer();// Bind appropriate array buffer to itgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,Index_Buffer);// Pass the vertex data to the buffergl.bufferData(gl.ELEMENT_ARRAY_BUFFER,newUint16Array(indices),gl.STATIC_DRAW);// Unbind the buffergl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,null);/*====================== Shaders =======================*/// Vertex shader source codevarvertCode="attribute vec3 coordinates;"+"void main(void) {"+" gl_Position = vec4(coordinates, 1.0);"+"}";// Create a vertex shader objectvarvertShader=gl.createShader(gl.VERTEX_SHADER);// Attach vertex shader source codegl.shaderSource(vertShader,vertCode);// Compile the vertex shadergl.compileShader(vertShader);// Fragment shader source codevarfragCode="void main(void) {"+" gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);"+"}";// Create fragment shader objectvarfragShader=gl.createShader(gl.FRAGMENT_SHADER);// Attach fragment shader source codegl.shaderSource(fragShader,fragCode);// Compile the fragmentt shadergl.compileShader(fragShader);// Create a shader program object to// store the combined shader programvarshaderProgram=gl.createProgram();// Attach a vertex shadergl.attachShader(shaderProgram,vertShader);// Attach a fragment shadergl.attachShader(shaderProgram,fragShader);// Link both the programsgl.linkProgram(shaderProgram);// Use the combined shader program objectgl.useProgram(shaderProgram);/* ======= Associating shaders to buffer objects =======*/// Bind vertex buffer objectgl.bindBuffer(gl.ARRAY_BUFFER,vertex_buffer);// Bind index buffer objectgl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,Index_Buffer);// Get the attribute locationvarcoord=gl.getAttribLocation(shaderProgram,"coordinates");// Point an attribute to the currently bound VBOgl.vertexAttribPointer(coord,3,gl.FLOAT,false,0,0);// Enable the attributegl.enableVertexAttribArray(coord);/*============= Drawing the Quad ================*/// Clear the canvasgl.clearColor(0.5,0.5,0.5,0.9);// Enable the depth testgl.enable(gl.DEPTH_TEST);// Clear the color buffer bitgl.clear(gl.COLOR_BUFFER_BIT);// Set the view portgl.viewport(0,0,canvas.width,canvas.height);// Draw the trianglegl.drawElements(gl.TRIANGLES,indices.length,gl.UNSIGNED_SHORT,0);
如何用html5绘制四边形,WebGL绘制四边形
最新推荐文章于 2021-07-14 20:59:12 发布