Loading in WebGL Shaders

Keith Peters
InstructorKeith Peters

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson we look at a better way of writing WebGL shaders - loading them in from script tags rather than concatenating JavaScript strings.

[00:00] As we'll soon be doing a lot more with shaders, let's figure out an easier way to write them rather than concatenating these JavaScript strings. A common way to do this is write the shaders in HTML script tags, and load them in via the DOM.

[00:14] Go to copy in a script from the MDN Developer site that does just what we need. It's called getShader. It lets you pass in a script ID, and then finds that script element using getElementById.

[00:27] It then loops through the text nodes, putting all the text into a variable called the source. Then it creates a shader using the type attribute of that script to determine if it should create a vertex shader or a fragment shader, and it adds the source to the shader and compiles it.

[00:43] It then even tests to see if the compilation was successful by querying the compile status of the shader. If all was OK, it returns the compiled shader.

[00:53] With that in place, we can go into the HTML and create two script tags. One will have an ID of shader-vs and a type of x-shader/x-vertex. That, obviously, will be our vertex shader. The fragment shader script will have an ID of shader-fs and a type of x-shader/x-fragment.

[01:16] Now I can copy the code for the vertex shader, paste it in here, and clean it up a bit. Then I can do the same for the fragment shader. Now, this will be much easier to edit than a concatenated string.

[01:37] Back in the createShaders function we can get rid of all this, and this, and this, and instead call getShader gl shader-vs for the vertex shader. The same for the fragment shader using the ID shader-fs.

[02:00] That's a whole lot cleaner overall. We run it and everything still works. To verify, I'll change some of the values we're passing in and make sure that they get to the shader and get rendered.

[02:12] Yes, it's definitely getting and compiling that shader code. Of course, you could do something beyond this such as storing your shader code in external files and using jQuery or something to load them in as text, and then create the shaders with that text. But the method we have here will do well enough for these lessons.

~ 2 years ago

Hi, why are script tags better? Is there a way to just have the shaders in a separate file, like *.shader or something? if you use ` (backtick) then you can write an entire code-block and don't need to concatenate strings line-by-line. Are script tags still better than that?

It still works, but the code you reference from the WebGL docs doesn't seem to be in those docs anymore. Is it okay to progress without using HTML script tags?