如何在WebGL中实现键盘输入?

我正在寻找实现键盘输入的方法,以允许用户更改所生成形状的颜色。下面是我实现的当前代码,该代码生成一个红色三角形。我将如何更改代码,以便如果用户在键盘上按下“ B”,则三角形的颜色将变为蓝色,如果按下“ G”,则三角形将变为绿色,等等。


var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '}\n';

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

function main() {

  var canvas = document.getElementById('webgl');

  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  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;
  }

  gl.clearColor(0, 0, 0, 0);

  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, n);
}

function initVertexBuffers(gl) {
  var vertices = new Float32Array([
    0, 0.5,   -0.5, -0.5,   0.5, -0.5
  ]);
  var n = 3; 


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


  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  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;
  }

  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);

  gl.enableVertexAttribArray(a_Position);

  return n;
}
评论
秋香先生
秋香先生

您可以通过将颜色作为统一值传递到着色器来轻松完成此工作

var FSHADER_SOURCE =
  'void main() {\n' +
  '  uniform vec3 uColor;' +
  '  gl_FragColor = vec4(uColor, 1.0);\n' +
  '}\n';

写下一个keyup事件处理程序,并根据event.key值设置统一值

document.addEventListener('keyup', (event) => {
    // program should be in scope and currently used by the WebGL rendering context 
    colorLocation = gl.getUniformLocation(program, "uColor")

    if (event.key == 'g')
    {
        gl.uniform3fv(colorLocation, [0.0, 1.0, 0.0])
        console.log('green')
    }
    else if (event.key == 'b')
    {
        gl.uniform3fv(colorLocation, [0.0, 0.0, 1.0])
        console.log('blue')
    }
}, false);

请记住,只有在设置完制服后重新调用图形时,此方法才起作用。您可以在此时调用它,也可以基于window.requestAnimationFrame()编写一些动画循环来适当地管理它

点赞
评论