HTML5 Game - A WebGL Initialization Function

Description

A WebGL Initialization Function

Demo

ResultView the demo in separate window

<!DOCTYPE html> 
<html> 
    <head> 
        <title>Canvas Demo</title> 
        <style> 
canvas { //from  www .j av  a  2s  .co  m
  border: 1px solid #000; 
} 
        </style> 
    </head> 
    <body> 
      <canvas id="myCanvas" width="200" height="200">Did You Know: Every time 
        you use a browser that doesn't support HTML5
      </canvas> 
      <script> 

function initWebGLOnCanvas(targetCanvas, opt_setup) { 
  if (opt_setup == null) { 
    opt_setup = false; 
  } 
  
  // Try and get the context. 
  let glContext = targetCanvas.getContext('webgl'); 
  if (glContext == null) { 
    glContext = targetCanvas.getContext('experimental-webgl'); 
    if (glContext == null) { 
      console.warn('WebGL is not supported in this browser.'); 
    } 
  } 
  
  if ((opt_setup === true) && (glContext != null)) { 
    // Set the clear color to black (rgba). 
    glContext.clearColor(0.0, 0.0, 0.0, 1.0); 
    glContext.depthFunc(glContext.EQUAL); 
    glContext.enable(glContext.DEPTH_TEST); 
    glContext.clear(glContext.COLOR_BUFFER_BIT|glContext.DEPTH_BUFFER_BIT); 
  } 
  return glContext; 
} 
let myCanvas = document.getElementById('myCanvas'); 
let myGLContext = initWebGLOnCanvas(myCanvas, true); 
      </script> 
    </body> 
</html>