我正在寻求实现键盘输入,以允许用户更改所生成形状的颜色。下面是我实现的当前代码,该代码生成一个红色三角形。我将如何更改代码,以便如果用户在键盘上按下“ 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值设置统一值
要设置默认颜色,请在程序准备就绪并使用后将其添加到您的init方法中>
u_Color = gl.getUniformLocation(gl.program, 'uColor') if (u_Color === null) { console.log('Failed to get color uniform location'); return; } // Default value: white color gl.uniform3fv(u_Color, [1.0, 1.0, 1.0])
要处理键盘事件,请将其添加到您的init方法中
document.addEventListener('keyup', onKeyUp, false);
并将此函数放入您的代码中(我让您设置变量和范围)
function onKeyUp(event)
{
if (event.key == 'g')
{
gl.uniform3fv(u_Color, [0.0, 1.0, 0.0])
}
else if (event.key == 'b')
{
gl.uniform3fv(u_Color, [0.0, 0.0, 1.0])
}
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}