Skip to content

Instantly share code, notes, and snippets.

@wolftype
Created September 24, 2016 21:03
Show Gist options
  • Save wolftype/4dde7b79d8e661f423bc9e6542534350 to your computer and use it in GitHub Desktop.
Save wolftype/4dde7b79d8e661f423bc9e6542534350 to your computer and use it in GitHub Desktop.
Create a WebGL Animation Loop
<html>
<script type="text/javascript">
var GL;
var timer = 0;
function initWebGL(){
// Get Canvas Element
var canvas = document.getElementById("glcanvas");
// Get A WebGL Context
GL = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
// Test for Success
if (!GL) {
alert("Unable to initialize WebGL. Your browser may not support it.");
}
// Set clear color to red, fully opaque
GL.clearColor(1.0, 0.0, 0.0, 1.0);
// Clear Screen
GL.clear(GL.COLOR_BUFFER_BIT| GL.DEPTH_BUFFER_BIT);
}
//ANIMATION FUNCTION (to be passed a callback) see also http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = ( function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
// if none of the above, use non-native timeout method
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
} ) ();
function animationLoop(){
// feedback loop requests new frame
requestAnimFrame( animationLoop );
// render function is defined below
render();
}
function render(){
timer++;
GL.clearColor( .5*(1+ Math.sin( timer/30.0 )), 0.0, .5*(1+Math.cos( timer/30.0 )), 1.0);
GL.clear(GL.COLOR_BUFFER_BIT| GL.DEPTH_BUFFER_BIT);
}
function start(){
initWebGL();
animationLoop();
}
</script>
<body onload = start() >
<canvas id="glcanvas" width=640 height=480 style = "margin:auto; display:block">
Oops, browser has no <code> canvas </code> tag support
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment