webgl 指南 click points

// ClickedPints.js (c) 2012 matsuda
// Vertex shader program
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '  gl_PointSize = 10.0;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
  '}\n';

function main() {
    // Retrieve <canvas> element
    var canvas = document.getElementById('webgl');

    // Get the rendering context for WebGL
    var  gl = canvas.getContext("experimental-webgl");
    if (!gl) {
        console.log('Failed to get the rendering context for WebGL');
        return;
    }

    // Initialize shaders
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        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) {
    /***
     * x 事件發生點當前文檔橫座標
     * y 事件發生點當前文檔縱座標
     * target 事件發生的目標元素---最先觸發的那一層
     * getBoundingClientRect
     * 事件發生節點元素的DOMRect對象,除去寬高外,都是相對於左上角的值
     */
  var x = ev.clientX; // 在body中x的座標
  var y = ev.clientY; // 在body中y的座標
  var rect = ev.target.getBoundingClientRect() ;
    /***************
     * x - rect.left代表鼠標點擊位置在canvas元素上的座標
     * 由於webgl座標原點在canvas元素的中間,因此,要先減去一半的canvas長度,
     * 再除canvas長度的一半即可得到繪製點在webgl座標系中的座標
     * 簡單一點,將canvas的寬高看做2,就容易理解了
     * 最後除canvas的寬度相當於歸一化
     * @type {number}
     */
  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 <canvas>

  gl.clear(gl.COLOR_BUFFER_BIT);

  var len = g_points.length;
  console.log(len)
  for(var i = 0; i < len; i += 2) {
    // Pass the position of a point to a_Position variable
    gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);

    // Draw
    gl.drawArrays(gl.POINTS, 0, 1);
    //繪製該點完成後,再繪製下一個點,那麼該點不是會被清空嗎?
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章