webGL通过鼠标单击绘制2D三角形

时间:2017-10-16 10:38:50

标签: javascript webgl

我想画一个鼠标点击的2D三角形。 已经制作了鼠标事件处理程序,可以看到点击鼠标的位置。 我在Buffer Object中写了Triangle的顶点位置。这将是三角形大小。 如何连接鼠标事件处理程序(函数单击)和三角形的位置(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;
}

错误讯息 - &gt; "image here"

2 个答案:

答案 0 :(得分:0)

由于您的顶点着色器尽可能简单,因此三角形在屏幕上的位置在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;

答案 1 :(得分:0)

你想要发生什么并不是很清楚。您想绘制一个具有多个三角形的网格,还是要绘制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);
  }

gl.bufferData需要typed array,而不是JavaScript本机数组,这是您传递的数据。

但是你也不清楚你要做什么。在initVertexBuffer中,您创建一个缓冲区并上传一个三角形(3个顶点)

然后在click中尝试用位数缓冲区替换位置缓冲区中的三角形,如果成功则删除三角形。它没有成功,因为你没有使用类型数组但是即使它成功了它也行不通,因为你最终删除了三角形。

真的选择一个地方可能有太多错误。我建议reading some other tutorials on WebGL

这是您的代码被黑客攻击

我在顶点着色器中添加了一个制服u_Offset。然后,我遍历click中的形状坐标,使用gl.uniform2f设置每个记录的偏移量,并为每个三角形调用gl.drawArrays

     //Vertex shader program
  var VSHADER_SOURCE = `
  attribute vec4 a_Position;
  uniform vec2 u_Offset;
  void main() {
    gl_Position = a_Position + vec4(u_Offset, 0, 0);
  }`;

   // Fragment shader program
  var FSHADER_SOURCE = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }`;
  
  var offsetLoc;

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

  // Get the rendering context for WebGL
  var gl = canvas.getContext("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;
  }
  
  offsetLoc = gl.getUniformLocation(gl.program, "u_Offset");

  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++) {
    // Draw
    gl.uniform2f(offsetLoc, shapes[i][0], shapes[i][1]);
    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;
}

function initShaders(gl, vsrc, fsrc) {
  // initShaders is really poorly designed. Most WebGL programs need multiple shader programs
  // but this function assumes there will only ever be one shader program
  // Also you should never assign values to the gl context.
  gl.program = twgl.createProgram(gl, [vsrc, fsrc]);
  gl.useProgram(gl.program);
  return gl.program;
}

main();
canvas { border: 1px solid black; }
<canvas id="webgl"></canvas>
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>