Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load GLSL file (WebGL) in HTML?

What I want:

<script src="shader.glsl" type="x-shader/x-fragment"></script>
<script src="shader.glsl" type="x-shader/x-vertex"></script>

or:

<script src="shader.frag" type="x-shader/x-fragment"></script>
<script src="shader.vert" type="x-shader/x-vertex"></script>

So I have 2 simple shader types:

  • type=x-shader/x-fragment

    precision mediump float;
    
    void main(void) {
        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
    
  • type=x-shader/x-vertex

    attribute vec3 aVertexPosition;
    
    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;
    
    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
    }
    

The shaders come from this WebGL tutorial


  1. Can I add these 2 types in one .glsl?
  2. If not are their other file formats for the shader types like:

    • .vert
    • .frag

Q: For what do I want to use this?
A: Dynamically loading my files from JavaScript and insert it to my HTML file.

Q: Do you want to know how to load dynamically files?
A: No that is irrelevant to the question "load GLSL file (WebGL) in HTML?"

Q: What do you want then?
A: Look at the What I want at the start of the question.

Q: Do you want to share your JavaScript import code?
A: Yes but I think that is irrelevant information to be able to answer the question

like image 293
TessavWalstijn Avatar asked Feb 23 '18 10:02

TessavWalstijn


People also ask

Does WebGL use GLSL?

WebGL programs consist of control code written in JavaScript and shader code (GLSL) that is executed on a computer's Graphics Processing Unit (GPU).

Does WebGL use shaders?

As mentioned in how it works WebGL requires 2 shaders every time you draw something. A vertex shader and a fragment shader. Each shader is a function.

What is gl_Position in WebGL?

gl_Position is the predefined variable which is available only in the vertex shader program. It contains the vertex position. In the above code, the coordinates attribute is passed in the form of a vector. As vertex shader is a per-vertex operation, the gl_position value is calculated for each vertex.


1 Answers

It is not possible this way.
See specs: https://www.w3.org/TR/html5/semantics-scripting.html#data-block

When used to include data blocks, the data must be embedded inline, the format of the data must be given using the type attribute, and the contents of the script element must conform to the requirements defined for the format used. The src, charset, async, defer, crossorigin, and nonce attributes must not be specified.

(So data blocks have to be inline, as shown in https://www.w3.org/TR/html5/semantics-scripting.html#dom-htmlscriptelement-text - then they can be accessed via .text or .textContent)

So revert to XMLHttpRequest (or some AJAX wrapper for it) if you want to load GLSL from separate files.

like image 157
tevemadar Avatar answered Oct 15 '22 00:10

tevemadar