2

The demos I have seen all define shaders in html, and get them by name. Is there a way in javascript to create them from strings?

Instead of:

  var fragmentShader = getShader(gl, "shader-fs");

something like:

var fragmentShader = createShader(gl,
"fragment code here "
);
1

3 Answers 3

2

Neither of the existing answers, I don't think, actually answer the question of how to set the source of a WebGL shader from a string in JavaScript. The missing bit is shaderSource:

const vertexShaderSource = `
attribute vec4 vertexPosition;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
void main() {
  gl_Position = projectionMatrix * modelViewMatrix * vertexPosition;
}
`;

const vertexShader = context.createShader(context.VERTEX_SHADER);
context.shaderSource(vertexShader, vertexShaderSource);
context.compileShader(vertexShader);
Sign up to request clarification or add additional context in comments.

Comments

0

I use this

var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);

and you can create your own shader program with GLSL in JavaScript like this

     var fragmentShaderText =
    [
    'precision mediump float;',
    '',
    'varying vec3 fragColor;',
    'void main()',
    '{',
    '   gl_FragColor = vec4(fragColor, 1.0);',
    '}',
    ].join('\n');

Comments

0

The best way I have seen so far:

var vertexShader = `attribute vec3 aVertexPosition;

uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;

void main(void) {
    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
}`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.