为什么着色器必须在web文件程序的html文件中? [英] Why do shaders have to be in html file for webgl program?

查看:298
本文介绍了为什么着色器必须在web文件程序的html文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到以下问题,有人问如何从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?

有一些精心设计的变通方法可以加载到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.

推荐答案

你没有使用< script> 标签来加载着色器程序。大多数教程和示例只是将它们用作容器来将字符串存储在网页的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);

这篇关于为什么着色器必须在web文件程序的html文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆