本文程序實現畫一個點的任務,以下圖。其中,點的位置直接給定(「硬編碼」)在頂點着色器中。javascript
整個程序包含兩個文件,分別是:html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>畫一個點</title> </head> <body onload="startup()"> <canvas id="myGLCanvas" width="640" height="480"> </canvas> </body> <script type="text/javascript" src="HelloPoint1.js"> </script> </html>
var gl; function createGLContext(canvas) { var names = ["webgl", "experimental-webgl"]; var context = null; for (var i=0; i < names.length; i++) { try { context = canvas.getContext(names[i]); //獲取webgl context繪圖上下文 } catch(e) {} if (context) { break; } } if (context) { context.viewportWidth = canvas.width; context.viewportHeight = canvas.height; } else { alert("Failed to create WebGL context!"); } return context; } function loadShader(type, shaderSource) { var shader = gl.createShader(type); gl.shaderSource(shader, shaderSource); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert("Error compiling shader" + gl.getShaderInfoLog(shader)); gl.deleteShader(shader); return null; } return shader; } function setupShaders() { //頂點着色器程序 var vertexShaderSource = 'void main(){ \n' + ' gl_Position = vec4(0.0, 0.0, 0.0, 1.0); \n' + //gl_Position指定了點的位置 ' gl_PointSize = 10.0; \n' + '} \n'; //片元着色器程序 var fragmentShaderSource = 'void main(){ \n' + ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); \n' + //gl_FragColor指定像素的顏色 '} \n'; var vertexShader = loadShader(gl.VERTEX_SHADER, vertexShaderSource); var fragmentShader = loadShader(gl.FRAGMENT_SHADER, fragmentShaderSource); var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Failed to setup shaders"); } gl.useProgram(shaderProgram); gl.program= shaderProgram; } function startup(){ var canvas = document.getElementById('myGLCanvas');//獲取<canvas>元素 gl = createGLContext(canvas); setupShaders(); gl.clearColor(0.0, 0.0, 0.0, 1.0);//指定清空<canvas>的顏色 gl.clear(gl.COLOR_BUFFER_BIT);//清空<canvas> gl.drawArrays(gl.POINTS, 0, 1);//從第0個元素開始,在指定位置(gl_Position)畫1個點 }
轉載請註明出處:http://www.cnblogs.com/opengl/p/7262596.htmljava