WebGL通过鼠标点击绘点

来源:互联网 发布:预包装食品网络销售 编辑:程序博客网 时间:2024/05/29 09:19

           现在我们在Canvas上面通过点击点来绘制点,依旧是在2d模式下,学过html和Javascript的肯定知道这需要注册事件响应函数,下面给大家看看运行结果:


也就是在鼠标点击位置会生成点(小红色正方形),接下来代码如下:

<!DOCTYPE html><html lang="en">  <head>    <meta charset="utf-8" />    <title>Draw a point with a mouse click</title>  </head>  <body onload="main()">    <canvas id="webgl" width="400" height="400">    Please use a browser that supports "canvas"    </canvas>    <script src="../Desktop/examples/examples/lib/cuon-utils.js"></script>    <script src="../Desktop/examples/examples/lib/webgl-utils.js"></script>  <script src="../Desktop/examples/examples/lib/webgl-debug.js"></script>    <script src="../Desktop/examples/examples/ch02/ClickedPoints.js"></script>  </body></html>

这里引用了三个库函数cuon-util.js,webgl-utils.js,ClickedPoints.js这三个文件是《Webgl 编程指南》这本书里面的源文件,百度一下就有很多,最重要的是js文件。

// JavaScript Documentvar VSHADER_SOURCE =  'attribute vec4 a_Position;\n' +  'void main() {\n' +  '  gl_Position = a_Position;\n' +  '  gl_PointSize = 10.0;\n' +  '}\n';// Fragment shader programvar 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 = getWebGLContext(canvas);  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 pressfunction 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);   g_points.push(x);   g_points.push(y);  gl.clear(gl.COLOR_BUFFER_BIT);  var len = g_points.length;  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);  }}

这里面大部分学过js的都应该能看懂,特别注意有以下几点:

首先顶点着色器和片元着色器分别传递的是顶点位置、大小和最后颜色。

从js里面传入顶点位置attribute变量。

然后是在事件函数里面求坐标比较复杂一点,主要是应为Webgl里面坐标和canvas里面坐标不一样,这里详情可以参照《WebGL 编程指南》这本书里面讲的很仔细。

0 0
原创粉丝点击