zoukankan      html  css  js  c++  java
  • WebGL绘制三角形

    本文程序实现绘制一个三角形的任务,如下图。

    HelloTriangle

    整个程序包含两个文件,分别是:

    1. HelloTriangle.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="600" height="600">
            </canvas>
        </body>
        <script type="text/javascript" src="HelloTriangle.js">
        </script>
    </html>
    

    2. HelloTriangle.js

    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 = 
          'attribute vec4 a_Position;
    ' +
          'void main() {
    ' +
          '  gl_Position = a_Position;
    ' +
          '  gl_PointSize = 10.0;
    ' +
          '}
    ';
        
        //片元着色器程序
        var fragmentShaderSource = 
          'void main(){ 
    ' +
          '    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); 
    ' + //gl_FragColor指定像素的颜色
          '} 
    ';                                         
         
      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 initVertexBuffers(gl) {
      var vertices = new Float32Array([
        0, 0.5,   -0.5, -0.5,   0.5, -0.5
      ]);
      var n = 3; // The number of vertices
    
      // Create a buffer object
      var vertexBuffer = gl.createBuffer();
      if (!vertexBuffer) {
        console.log('Failed to create the buffer object');
        return -1;
      }
    
      // Bind the buffer object to target
      gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
      // Write date into the buffer object
      gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    
      var a_PosLocation = gl.getAttribLocation(gl.program, 'a_Position');
      if (a_PosLocation < 0) {
        console.log('Failed to get the storage location of a_Position');
        return -1;
      }
      // Assign the buffer object to a_Position variable
      gl.vertexAttribPointer(a_PosLocation, 2, gl.FLOAT, false, 0, 0);
    
      // Enable the assignment to a_Position variable
      gl.enableVertexAttribArray(a_PosLocation);
    
      return n;
    }
    
    function startup(){
        var canvas = document.getElementById('myGLCanvas');//获取<canvas>元素
        gl = createGLContext(canvas);
        setupShaders(); 
    
      // Write the positions of vertices to a vertex shader
      var n = initVertexBuffers(gl);
      if (n < 0) {
        console.log('Failed to set the positions of the vertices');
        return;
      }
    
      // Specify the color for clearing <canvas>
      gl.clearColor(0, 0, 0, 1);
    
      // Clear <canvas>
      gl.clear(gl.COLOR_BUFFER_BIT);
    
      // Draw the rectangle
      gl.drawArrays(gl.TRIANGLES, 0, n);
     }
    

    参考代码

    1. Hello Point——WebGL, http://www.cnblogs.com/idealer3d/p/3513838.html
    2. Professional WebGL Programming: Developing 3D Graphics for the Web,Listing 2-1,http://media.wiley.com/product_ancillary/60/11199688/DOWNLOAD/Listing-2-1.html
    3. WebGL Programming Guide, https://sites.google.com/site/webglbook/

    转载请注明出处:http://www.cnblogs.com/opengl/p/7274033.html

  • 相关阅读:
    Delphi XE2 update4 很快就要来了
    树型菜单表的合并。
    VS宏 之 选中解决方案中的文件
    Mvc,接收复杂对象。
    SQL 2008 CLR开发自定义聚合函数
    数据库主键按业务规则生成的解决方案。
    一些独特的语言思考
    vs环境设置
    SqlServer 2005+ 开发问题
    记录 VS 中的生成时间
  • 原文地址:https://www.cnblogs.com/opengl/p/7274033.html
Copyright © 2011-2022 走看看