ch03/TranslatedTriangle
Example from the book "WebGL Programming Guide" by Matsuda & 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;
uniform vec4 u_Translation;
void main()
{
gl_Position = a_Position + u_Translation;
}
</script>
<script type="x-shader/x-fragment" id="FragmentShader">
void main()
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
</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>
JavaScript
// The translation distance for x, y, and z direction
var Tx = 0.5, Ty = 0.5, Tz = 0.0;
main();
window.onload = main;
function main()
{
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl)
{
console.log('Failed to get the rendering context for WebGL');
return;
}
// Get shader elements
var vShaderElement = document.getElementById("VertexShader");
var fShaderElement = document.getElementById("FragmentShader");
if (vShaderElement == null)
{
console.log("Failed to get the vertex shader element");
return;
}
if (fShaderElement == null)
{
console.log("Failed to get the fragment shader element");
return;
}
// Get shader sources
var vShaderSource = vShaderElement.firstChild.textContent;
var fShaderSource = fShaderElement.firstChild.textContent;
// Initialize shaders
if (!initShaders(gl, vShaderSource, fShaderSource))
{
console.log('Failed to intialize shaders.');
return;
}
// 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;
}
// Pass the translation distance to the vertex shader
var u_Translation = gl.getUniformLocation(gl.program, 'u_Translation');
if (!u_Translation)
{
console.log('Failed to get the storage location of u_Translation');
return;
}
gl.uniform4f(u_Translation, Tx, Ty, Tz, 0.0);
// 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);
}
function initVertexBuffers(gl)
{
var vertices = new Float32Array([
0, 0.5, -0.5, -0.5, 0.5, -0.5
]);
var n = 3;...