ch10/RotatingTriangle_contextLost
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;
uniform mat4 u_ModelMatrix;
void main()
{
gl_Position = u_ModelMatrix * a_Position;
}
</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>
<script src="https://dl.dropboxusercontent.com/s/jw3p82lq1cjwekg/cuon-matrix.js"></script>
JavaScript
// RotatingTriangle_contextLost.js (c) 2012 matsuda
// This is an example from the book "WebGL Programming Guide"
// by Kouichi Matsuda and Rodger Lea
// Current rotation angle
var ANGLE_STEP = 45.0;
// Current rotation angle
var g_currentAngle = 0.0; // Changed from local variable to global variable
var g_requestID; // The return value of requestAnimationFrame()
// Last time that this function was called
var g_last = Date.now();
main();
//window.onload = main;
function main()
{
// Retrieve <canvas> element
var canvas = document.getElementById('webgl');
// Register event handler for context lost and context restored events
canvas.addEventListener('webglcontextlost', contextLost, false);
canvas.addEventListener('webglcontextrestored', function (ev) { start(canvas); }, false);
start(canvas); // Perform WebGL related processes
}
function start(canvas)
{
// 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...