appendix/CoordinateSystem
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;
varying vec4 v_Color;
void main()
{
gl_Position = 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.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.clearColor(0.0, 0.0, 0.0, 1.0); // Specify the color for clearing <canvas>
gl.clear(gl.COLOR_BUFFER_BIT); // Clear <canvas>
gl.drawArrays(gl.TRIANGLES, 0, n); // Draw the triangles
}
function initVertexBuffers(gl)
{
var pc = 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 triangle 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 pcbuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, pcbuffer);
gl.bufferData(gl.ARRAY_BUFFER, pc, gl.STATIC_DRAW);
var FSIZE = pc.BYTES_PER_ELEMENT; // The number of byte
var STRIDE = numVertex + numColor; // Stride
// Assign the vertex coordinates to attribute variable and enable the assignment
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
gl.vertexAttribPointer(a_Position, numVertex, gl.FLOAT, false, FSIZE * STRIDE, 0);
...