ch03/RotatedTriangle
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">
// x' = x cosβ - y sinβ
// y' = x sinβ + y cosβ Equation 3.3
// z' = z
attribute vec4 a_Position;
uniform float u_CosB, u_SinB;
void main()
{
gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
gl_Position.y = a_Position.x * u_SinB + a_Position.y * u_CosB;
gl_Position.z = a_Position.z;
gl_Position.w = 1.0;
}
</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 rotation angle
var ANGLE = 90.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 data required to rotate the shape to the vertex shader
var radian = Math.PI * ANGLE / 180.0; // Convert to radians
var cosB = Math.cos(radian);
var sinB = Math.sin(radian);
var u_CosB = gl.getUniformLocation(gl.program, 'u_CosB');
var u_SinB = gl.getUniformLocation(gl.program, 'u_SinB');
if (!u_CosB || !u_SinB)
{
console.log('Failed to get the storage location of u_CosB or u_SinB');
return;
}
gl.uniform1f(u_CosB, cosB);
gl.uniform1f(u_SinB, sinB);
// Specify the color for clearing <canvas>
gl.clearColor(0, 0, 0, 1);
// Clear <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// Draw the rectangle
...