WebGL 鼠标点击绘制点
<!-- * @Author: 苹果园dog * @Date: 2020-11-19 10:59:00 * @LastEditTime: 2020-11-19 18:19:23 * @LastEditors: Please set LastEditors * @Description: WebGL中的绘制操作实际上是在颜色缓冲区中绘制的,绘制结束后系统将缓冲区中的内容显示在屏幕上, 然后颜色缓冲区就会被重置,其中的内容会丢失。因此我们有必要将每次鼠标点击的位置保存下来。 * @FilePath: \web\webgl\study\clickedPoints.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>clickedPoints</title> </head> <body onload="main()"> <canvas id="webgl" width="800" height="800"> </canvas> <script src="../lib/webgl-utils.js"></script> <script src="../lib/webgl-debug.js"></script> <script src="../lib/cuon-utils.js"></script> <script> //顶点着色器 var VSHADER_SOURCE=` attribute vec4 a_Position; void main(){ gl_Position =a_Position; gl_PointSize=15.0; } `; //片元着色器,精度限定词用来指定变量的范围和精度 var FSHADER_SOURCE=` precision mediump float; uniform vec4 u_FragColor; void main(){ gl_FragColor=u_FragColor; } `; function main() { //获取<canvas>元素 var canvas = document.getElementById('webgl'); //获取WebGL上下文 var gl = getWebGLContext(canvas); if (!gl) { console.log('获取WebGL绘图上下文失败!'); return; } //初始化着色器 if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) { console.log('初始化着色器失败!'); return; } //获取attribute变量的存储位置 var a_Position = gl.getAttribLocation(gl.program, 'a_Position'); if (a_Position < 0) { console.log('获取a_Position变量的存储位置失败!'); return; } var u_FragColor=gl.getUniformLocation(gl.program,'u_FragColor'); //如果uniform变量不存在,或其命名使用了保留字前缀,那么函数的返回值将是null,而不是-1 if(!u_FragColor){ console.log('获取u_FragColor变量的存储位置失败!'); return; } canvas.onmousedown=function(ev){ click(ev,gl,canvas,a_Position,u_FragColor); } //设置canvas背景色 gl.clearColor(0.0, 0.0, 0.0, 1.0); //清除canvas gl.clear(gl.COLOR_BUFFER_BIT); } var g_points=[]; var g_colors=[];//存储点颜色的数组 function click(ev,gl,canvas,a_Position,u_FragColor){ var x=ev.clientX;//鼠标点击处的X坐标 var y=ev.clientY;//鼠标点击处的Y坐标 var rect =ev.target.getBoundingClientRect(); //将浏览器绘图区坐标系下的坐标转换为webgl坐标系下的坐标 x=((x-rect.left)-canvas.width/2)/(canvas.width/2); y=(canvas.height/2-(y-rect.top))/(canvas.height/2); g_points.push([x,y]); if(x>=0&&y>=0){ g_colors.push([1.0,0.0,0.0,1.0]); }else{ g_colors.push([1.0,1.0,1.0,1.0]); } gl.clear(gl.COLOR_BUFFER_BIT); var len=g_points.length; for (let index = 0; index < g_points.length; index++) { var xy=g_points[index]; var rgba=g_colors[index]; const element = g_points[index]; gl.vertexAttrib3f(a_Position,xy[0],xy[1],0.0); gl.uniform4f(u_FragColor,rgba[0],rgba[1],rgba[2],rgba[3]); gl.drawArrays(g_points,0,1); } } </script> </body> </html>