ch02/HelloPoint2

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">
        attribute vec4 a_Position; // Attribute variable

        void main()
        {
            gl_Position = a_Position;
            gl_PointSize = 10.0;
        }
    </script>

    <script type="x-shaser/x-fragment" id="FragmentShader">
        void main()
        {
            gl_FragColor = vec4(0.0, 1.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

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 source
    var vShaderElement = document.getElementById("VertexShader");
    var fShaderElement = document.getElementById("FragmentShader");
    if (vShaderElement == null || fShaderElement == null)
    {
        console.log("Failed to get the vShaderElement or fShaderElement");
        return;
    }
    var vShaserSource = vShaderElement.firstChild.textContent;
    var fShaserSource = fShaderElement.firstChild.textContent;

    // Initialize shaders
    if (!initShaders(gl, vShaserSource, fShaserSource))
    {
        console.log('Failed to intialize shaders.');
        return;
    }

    // Get the storage location of a_Position
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0)
    {
        console.log('Failed to get the storage location of a_Position');
        return;
    }

    // Pass vertex position to attribute variable
    gl.vertexAttrib3f(a_Position, 0.0, 0.5, 0.0);

    // Specify the color for clearing <canvas>
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    // Clear <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    // Draw
    gl.drawArrays(gl.POINTS, 0, 1);
}