我可以从外部文本文件将着色器加载到我的JavaScript代码中吗? [英] Can I load a shader into My JavaScript code from an external text file?
问题描述
我学习 WebGL
.我看到该教程在JavaScript代码中包含了着色器的代码,就像通常的字符串一样.例如:
I learn WebGL
. I see the tutorial has the code of shaders inside of JavaScript code as a usual string. For example:
var VSHADER_SOURCE =
'void main(){\n' +
' gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n' +
' gl_PointSize = 10.0;\n' +
'}\n';
我想将着色器的代码放入外部文本文件中,并在必要时将其加载到我的JavaScript代码中.我该怎么办?我不想在同一源代码文件中混合使用JavaScript代码和着色器代码.
I want to place the code of my shaders into the external text files and load them into my JavaScript code when it necessary. How can I do it right? I don't want mix the JavaScript code and shader code in the same source code file.
我在LoadShaderFromFiles.html
此处进行了查找,但没有找到"正常工作(我使用的是Google Chrome版本40.0.2214.111 m).我在此示例中遇到错误:
I looked the sample LoadShaderFromFiles.html
here, but it doesn't work (I use the Google Chrome version 40.0.2214.111 m). I get errors for this sample:
推荐答案
这根本不是webgl的问题,但是您可以使用XMLHttpRequest
加载代码,但前提是必须启动本地开发服务器.出于安全原因.
It's not at all a webgl question, but you can load the code with a XMLHttpRequest
but only if you start a local dev server. For security reasons.
Python附带了一个非常易于使用的服务器.因此,如果您已将python安装了cd并安装到要在命令行中提供的目录中,只需键入
Python comes with a very easy to use server. So if you have python installed cd into the directory you want to serve in the command line and just type
python -m SimpleHttpServer 8001
然后,您可以使用浏览器导航到localhost:8001
,并且应该能够在不损害安全性的情况下将请求发送到本地文件.
then you can navigate with your browser to localhost:8001
and should be able to send requests to your local files without compromising your security.
另一种设置解决方案的技巧比较棘手,那就是使用es6,这是具有出色模板字符串的新版javascript,非常适合在javascript中嵌入着色器代码.
Another, a bit more tricky to set up solution would be to use es6, the new version of javascript with awesome template strings, really great for embedding shader code in javascript.
es6对浏览器的支持仍然很低,因此您可能需要使用一段时间的编译器才能将其编译回es5(当前广泛支持的javascript),例如
es6 support is browsers is still very low so you may have to use a transpiler for a while to compile it back to es5 ( currently widely supported javascript ), for example traceur.
这是您的示例使用es6模板字符串(以及其他非常有用的功能)的样子,这些字符串可以跨越多行:
Here's what your example looks like with es6 template strings (among other really useful features) those can just span multiple lines:
var VSHADER_SOURCE = `
void main(){
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
gl_PointSize = 10.0;
}
`;
人们使用的另一种技术是在html标记中添加脚本标签并加载其.textContent
.
Another technique people use is to add script tags in html markup and load their .textContent
.
html:
<script type="glsl" id="VSHADER_SOURCE">
void main(){
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
gl_PointSize = 10.0;
}
</script>
js:
var fsCode = document.getElementById("VSHADER_SOURCE").textContent;
这篇关于我可以从外部文本文件将着色器加载到我的JavaScript代码中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!