ch02/ClickedPoints

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;

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

    <script type="x-shader/x-fragment" id="FragmentShader">
        void main()
        {
            gl_FragColor = vec4(0.0, 1.0, 1.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 elements
    var vShaderElement = document.getElementById("VertexShader");
    var fShaderElement = document.getElementById("FragmentShader");
    if (vShaderElement != null || fShaderElement != null)
    {
        console.log("Failed to get the shader element");
    }

    // Get shader source
    var vShaderSource = vShaderElement.firstChild.textContent;
    var fShaderSource = fShaderElement.firstChild.textContent;

    // Initialize shaders
    if (!initShaders(gl, vShaderSource, fShaderSource))
    {
        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;
    }

    // Register function (event handler) to be called on a mouse press
    canvas.onmousedown = function (ev) { click(ev, gl, canvas, a_Position); };

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

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

var g_points = []; // The array for the position of a mouse press
function click(ev, gl, canvas, a_Position)
{
    var x = ev.clientX; // x coordinate of a mouse pointer
    var y = ev.clientY; // y coordinate of a mouse pointer
    var rect = ev.target.getBoundingClientRect();

    x = ((x - rect.left) - canvas.width / 2) / (canvas.width / 2);
    y = (canvas.height / 2 - (y - rect.top)) / (canvas.height / 2);
    // Store the coordinates to g_points array
    g_points.push(x); g_points.push(y);

    // Clear...