appendix/CoordinateSystem_viewVolume
This is an example from the book "WebGL Programming Guide" by Kouichi Matsuda and Rodger Lea
by Ivan Enzhaev
HTML
<canvas id="webgl" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script type="x-shader/x-vertex" id="VertexShader">
attribute vec4 a_Position;
attribute vec4 a_Color;
uniform mat4 u_MvpMatrix;
varying vec4 v_Color;
void main()
{
gl_Position = u_MvpMatrix * a_Position;
v_Color = a_Color;
}
</script>
<script type="x-shader/x-fragment" id="FragmentShader">
precision mediump float;
varying vec4 v_Color;
void main()
{
gl_FragColor = v_Color;
}
</script>
<script src="https://dl.dropboxusercontent.com/s/ylw7v7a44xtrwv0/webgl-utils.js"></script>
<script src="https://dl.dropboxusercontent.com/s/iz1n21c8xafd76n/webgl-debug.js"></script>
<script src="https://dl.dropboxusercontent.com/s/subm1yzylxuao8v/cuon-utils.js"></script>
<script src="https://dl.dropboxusercontent.com/s/jw3p82lq1cjwekg/cuon-matrix.js"></script>
JavaScript
// CoordinateSystem_viewVolume.js (c) 2012 matsuda
// This is an example from the book "WebGL Programming Guide"
// by Kouichi Matsuda and Rodger Lea
main();
//window.onload = main;
function main()
{
var canvas = document.getElementById('webgl'); // Retrieve <canvas> element
var gl = getWebGLContext(canvas); // Get the rendering context for WebGL
var vShaderElement = document.getElementById("VertexShader"); // Get shader elements
var fShaderElement = document.getElementById("FragmentShader");
var vShaderSource = vShaderElement.firstChild.textContent; // Get shader sources
var fShaderSource = fShaderElement.firstChild.textContent;
initShaders(gl, vShaderSource, fShaderSource); // Initialize shaders
var n = initVertexBuffers(gl); // Set the vertex information
gl.enable(gl.DEPTH_TEST); // Enable the hidden surface removal function
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Set the clear color for <canvas>
// Get the storage location of u_MvpMatrix
var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
var mvpMatrix = new Matrix4();
mvpMatrix.setOrtho(-1, 1, -1, 1, 0, 1); // Set the viewing volume
// Pass the view matrix to u_MvpMatrix
gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Clear the color buffer
gl.drawArrays(gl.TRIANGLES, 0, n); // Draw the triangles
}
function initVertexBuffers(gl)
{
var verticesColors = new Float32Array([ // Vertex coordinates and color
0.0, 0.5, -0.1, 0.0, 0.0, 1.0, // The front blue one
-0.5, -0.5, -0.1, 0.0, 0.0, 1.0,
0.5, -0.5, -0.1, 1.0, 1.0, 0.0,
0.5, 0.4, -0.5, 1.0, 1.0, 0.0, // The red one is behind
-0.5, 0.4, -0.5, 1.0, 0.0, 0.0,
0.0, -0.6, -0.5, 1.0, 0.0, 0.0,
]);
var numVertex = 3; var numColor = 3; var n = 6;
// Create a buffer object and write data to it
var vertexPositionbuffer =...