WebGLその2:初期化

前回のプログラム(http://d.hatena.ne.jp/sanoh/20120326)をJavaScriptらしく、「index.html」「webglut00.js」に分解してみました。

■index.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>SanoWebGLSample02.html</title>
</head>
<script type="text/javascript" src="webglut00.js"></script>
<script>
//------------------------------------------------------------------------
//    
//------------------------------------------------------------------------
var    gl;                //gl用コンテキスト
function init()
{
    //初期化
    gl    = Ginit( document.getElementById("c") );
    //    メインループ登録
    setInterval( "MainLoop()", 33 );
}
//------------------------------------------------------------------------
//    メインループ
//------------------------------------------------------------------------
function MainLoop()
{
    // 画面クリア
    Gclear();
}
</script>
<body onload="init();">
<canvas id="c" style="border:none" width="640" height="480">
</body>
</html>

■webglut00.js

(function(np){    
    var gl = null;
    np.Ginit = function( canvas )
    {
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight= canvas.height;
        }
        catch (e) {}

        if (!gl) {
            alert("WebGL に対応してないです");
            return;
        }
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clearDepth(1.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);
        return gl;
    };
    np.Gclear = function()
    {
        gl.viewport( 0, 0, gl.viewportWidth, gl.viewportHeight );
        gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    }
})(this);

こうしておけば、あとで使いやすいですね。