Javascript webGL使用鼠标单击绘制二维三角形

Javascript webGL使用鼠标单击绘制二维三角形,javascript,webgl,Javascript,Webgl,我想在鼠标点击的地方画一个二维三角形。 已经创建了鼠标事件处理程序,可以看到鼠标单击的点。 我在缓冲区对象中写下三角形的顶点位置。它将是三角形大小。 如何连接鼠标事件处理程序(函数单击)和三角形位置(positionBuffer) 你能给我一个答案吗 //Vertex shader program var VSHADER_SOURCE = 'attribute vec4 a_Position;\n' + 'void main() {\n' + ' gl_Positio

我想在鼠标点击的地方画一个二维三角形。 已经创建了鼠标事件处理程序,可以看到鼠标单击的点。 我在缓冲区对象中写下三角形的顶点位置。它将是三角形大小。 如何连接鼠标事件处理程序(函数单击)和三角形位置(positionBuffer) 你能给我一个答案吗

     //Vertex shader program
  var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\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 = 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;
  }

  var n = initVertexBuffers(gl);
  if(n < 0){
    console.log('Failed to set the positions of the vertices');
    return;
  }


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

  // 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 shapes = [];  // The array for the position of Triangle with mouse click

function click(ev, gl, canvas) {
  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 shapes array
  shapes.push([x,y]);

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


  var len = shapes.length;
  for(var i = 0; i < len; i++) {

    gl.bufferData(gl.ARRAY_BUFFER, shapes[i], gl.STATIC_DRAW);
  }
   // Draw
    gl.drawArrays(gl.TRIANGLES, 0, 3);
}


//Make the BO for making triangle
function initVertexBuffers(gl){

  var vertices = new Float32Array([
     0.0, 0.1,
    -0.1, -0.1,
    0.1, -0.1,
    ]);
  var n = 3;

  //Create a buffer Object
  var positionBuffer = gl.createBuffer();
  if(!positionBuffer){
    console.log('Failed to create the buffer object');
    return -1;
  }

  //Bind the buffer object to target
  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  //Write date into the buffer object
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

    //Assign the buffer object to a_Position variable
  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 -1;
  }

  //Connect the assignment to a_Position variable
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  //Enable the assignment to a_Position variable
  gl.enableVertexAttribArray(a_Position);

  return n;
}
//顶点着色器程序
var-VSHADER_源=
'属性向量4 a_位置\不+
'void main(){\n'+
'gl\U位置=a\U位置;\n'+
'}\n';
//片段着色器程序
var FSHADER_源=
'void main(){\n'+
'gl_FragColor=vec4(1.0,0.0,0.0,1.0);\n'+
'}\n';
函数main(){
//检索元素
var canvas=document.getElementById('webgl');
//获取WebGL的渲染上下文
var gl=getWebGLContext(画布);
如果(!gl){
log('未能获取WebGL的呈现上下文');
回来
}
//初始化着色器
if(!initShaders(gl、VSHADER_源、FSHADER_源)){
log('初始化着色器失败');
回来
}
var n=initVertexBuffers(gl);
if(n<0){
console.log('未能设置顶点的位置');
回来
}
//鼠标按下时要调用的注册函数(事件处理程序)
canvas.onmousedown=函数(ev){单击(ev,gl,canvas)};
//指定要清除的颜色
gl.clearColor(0.0,0.0,0.0,1.0);
//清楚的
总账清除(总账颜色缓冲位);
}
变量形状=[];//鼠标单击三角形位置的数组
功能点击(ev、gl、画布){
var x=ev.clientX;//鼠标指针的x坐标
var y=ev.clientY;//鼠标指针的y坐标
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);
//将坐标存储到形状数组中
推压([x,y]);
//清楚的
总账清除(总账颜色缓冲位);
var len=shapes.length;
对于(变量i=0;i
错误消息->

由于顶点着色器尽可能简单,因此屏幕上三角形的位置在X上为-1到1,在Y上为1到-1(WebGL的Y向上为正)

因此,下面的转换应该可以做到这一点:

// convert mouse cursor to canvas top-left relative
x -= rect.left;
y -= rect.top;

// normalize with range -1 to 1 and invert Y
posX = (2 * (x / canvas.width)) - 1;
posY = (2 * ((canvas.height - y) / canvas.height)) - 1;

现在还不清楚你想发生什么。是要使用多个三角形绘制一个网格,还是要绘制N个三角形

在任何情况下,这段代码都没有意义

var shapes = [];  // The array for the position of Triangle with mouse click

function click(ev, gl, canvas) {
  ...    

  // Store the coordinates to shapes array
  shapes.push([x,y]);

  ...

  var len = shapes.length;
  for(var i = 0; i < len; i++) {

    gl.bufferData(gl.ARRAY_BUFFER, shapes[i], gl.STATIC_DRAW);
  }
canvas{边框:1px纯黑;}


我更改了代码作为您的答案,但仍有错误。。。在文章中附上我的错误页面图片。这个错误与你的三角形位置无关。它与顶点缓冲区和指针有关。我认为你应该用另一种方式来构造你的代码,你使用WebGL的方式其实并不合适。开始时要更加循序渐进和“愚蠢”:一个“requestanimframe”循环,循环中包含:绑定缓冲区,设置attrib指针,绘制。外部循环:鼠标点击时更新缓冲区数据。这就是我想要做的。谢谢你的帮助