为什么着色器必须在 webgl 程序的 html 文件中? [英] Why do shaders have to be in html file for webgl program?
问题描述
我看到以下问题,有人问如何从 html 中删除着色器:WebGL - 是否有替代在 HTML 中嵌入着色器的方法?
I have seen the following question where someone asked how to remove shaders from html: WebGL - is there an alternative to embedding shaders in HTML?
在包含问题答案中建议的着色器的文件中加载了详细的解决方法.
There are elaborate workarounds to load in a file containing the shader suggested in the answers to the question.
在我看到的教程中,着色器代码是直接嵌入到html中的.javascript 代码使用 getElementById 引用它.但是由于多种原因,将着色器直接嵌入到 html 中是很丑陋的.为什么我不能直接使用 src= 属性在外部引用它?
In the tutorial I saw, the shader code is embedded directly in the html. The javascript code refers to it using getElementById. But it's ugly embedding the shader directly in the html for many reasons. Why can't I just refer to it externally using the src= attribute?
<script type="x-shader/x-fragment" id="shader-fs" src="util/fs"></script>
以上不行,我只是想知道为什么不行.这显然与脚本本身的限制有关,但我不明白.
The above doesn't work, I just want to know why not. This is clearly something to do with limitations on script itself, but I don't get it.
推荐答案
您根本不必使用 标签来加载着色器程序.大多数教程和示例只是将它们用作在网页的 DOM 中存储字符串的容器.脚本类型
"x-shader/x-fragment"
对于 Web 浏览器没有意义,因此它们不执行脚本.然而,它们确实将该标签的内容作为字符串存储在 DOM 中,然后可以由真实"脚本访问.这仅在脚本内容在 HTML 文件中时有效.当您通过 src 属性加载脚本时,内容不会成为脚本标签的文本子节点,因此无法通过 DOM 树访问.
You don't have to use <script>
tags at all to load a shader program. Most tutorials and examples just use them as a container to store a string in the DOM of the webpage. The script type "x-shader/x-fragment"
is meaningless for web browsers, so they don't execute the script. They do, however, store the content of that tag as a string in the DOM which can then later be accessed by "real" scripts. This only works when the script content is in the HTML file. When you load the script via a src attribute, the content does not become a text childnode of the script tag and thus can not be accessed through the DOM tree.
您也可以将着色器的源代码作为字符串存储在 Javascript 文件中:
You can just as well store the sourcecode for the shader as a string in a Javascript file:
// myVertextShader.glsl.js
var myVertexShaderSrc =
"attribute vec3 pos;"+
"void main() {"+
" gl_Position = vec4(pos, 1.0);"+
"}"
;
然后你会像这样编译着色器:
You would then compile the shader like this:
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, myVertexShaderSrc);
gl.compileShader(vertexShader);
gl.attachShader(program, vertexShader);
这篇关于为什么着色器必须在 webgl 程序的 html 文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!