0

我正在尝试使用 WebGL 和 Javascript 实现 3D 场景。最后一个场景应该显示一个长方体,四面都是较小的长方体、金字塔和球体。较小的球体必须与大长方体一起旋转。我实现了 Phong Shading,效果很好。现在我想用显示场景的画布右侧的三个滑块更改shininesslightPos和的值。lightIntensity闪亮的滑块显然不起作用,我更加纠结于其他两个滑块,因为lightPos它们lightIntensityvec3常量。三个变量的代码如下所示:

const vec3 lightPos = vec3(1.0,-1.0,1.0);
float shininess = 16.0;
const vec3 lightIntensity = vec3(1.0, 1.0, 1.0);

目前,光泽度滑块如下所示:

<input id="shininess" type="range" min="1" max="50"></input>
var shininessElement = document.getElementById("shininess");
shininessElement.onchange = function(){
shininess = shininessElement.value;
window.requestAnimationFrame(animate);

我很确定我做错了什么,但一项研究没有产生任何结果,我不知道下一步该做什么,所以我非常感谢你的帮助。如果您需要完整的代码,请告诉我。

4

1 回答 1

0

You probably should read some other tutorials on WebGL. In particular you can't set shininess unless you make it a uniform, then look up the uniform's location and set it with gl.uniform???.

Here's simple example of using a slider to set a value and then sending that value to a shader by setting a uniform variable in the shader.

const gl = document.querySelector("canvas").getContext('webgl');

const vs = `
 void main() {
   gl_Position = vec4(0, 0, 0, 1);
   gl_PointSize = 100.0;
 }
`;

const fs = `
  precision mediump float;
  uniform float shininess;
  void main() {
    gl_FragColor = vec4(shininess, 0, 0, 1);
  }
`;

// compiles shaders, links program
const prg = twgl.createProgram(gl, [vs, fs]);
const shininessLocation = gl.getUniformLocation(prg, "shininess");

let shininess = .5;

draw();

function draw() {
  gl.useProgram(prg);
  gl.uniform1f(shininessLocation, shininess);
  gl.drawArrays(gl.POINTS, 0, 1);
}

document.querySelector("input").addEventListener('input', (e) => {
  shininess = e.target.value / 100;
  draw();
});
<script src="https://twgljs.org/dist/3.x/twgl.min.js"></script>
<canvas></canvas>
<input type="range" min="0" max="100" value="50" />

于 2017-08-18T04:38:14.500 回答