0

I am making app by using javascript and webgl. I want to get uniform value from shader with javascript code.

This is my vertex shader

  var VertexShaderCode=  "precision mediump float;"+
        "attribute vec3 vertexPos;" +
        "uniform mat4 modelViewMatrix;" +
        "uniform mat4 projectionMatrix;" +
        "uniform float pointSize;"+
        "void main(void) {" +
           "gl_Position= projectionMatrix*modelViewMatrix*vec4(vertexPos, 1.0);" +
            "gl_PointSize=pointSize;"+
        "}"

I want to get pointSize value by using javascript and then I want to use this value in javascript code.

Any ideas?What should I do?

  • 1
    As a side note, you can also create multi-line string literals using backticks for better readability. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility) for browser support – peabrainiac Oct 18 '19 at 18:49
  • [See this answer about more edit friendly ways to store shaders](https://stackoverflow.com/a/14248861/128511) – gman Oct 19 '19 at 04:18

1 Answers1

2

Since you're setting the uniform you should already know the value. But if for some reason you want to look it up then you just call gl.getUniform(program, location)

Example:

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

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

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

// compile shaders, link program
const program = twgl.createProgram(gl, [vs, fs]);

const fooLocation = gl.getUniformLocation(program, 'foo');

// set foo
gl.useProgram(program);
gl.uniform1f(fooLocation, 123.4);

// get foo
console.log('foo:', gl.getUniform(program, fooLocation));
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>
gman
  • 100,619
  • 31
  • 269
  • 393