I'm trying to render a GLSL shader on a Web Application, for which I use glslCanvas. The canvas used for rendering has a data-fragment attribute which is supposed to be able to take a string literal of GLSL code to construct the shader. However, when I use Django context to pass the shader code as the value to that attribute, the shader doesn't seem to work. However, when I instead create a script-tag and load the exact same code via JavaScript, it works. I assume the load function does some kind of formatting that is important for pattern matching, however for my purposes it would be a lot more preferable if I could just use the HTML-attribute. Is that possible?
Example shader:
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
// Plot a line on Y using a value between 0.0-1.0
float plot(vec2 st) {
return smoothstep(0.02, 0.0, abs(st.y - st.x));
}
void main() {
vec2 st = gl_FragCoord.xy/u_resolution;
float y = st.x;
vec3 color = vec3(y);
// Plot a line
float pct = plot(st);
color = (1.0-pct)*color+pct*vec3(0.0,1.0,0.0);
gl_FragColor = vec4(color,1.0);
}
HTML (the script and canvas tags were tested seperately, just put here together for brevity):
<div id="shader-container">
<hr>
<!-- Doesn't display the shader -->
<canvas class="glslCanvas" data-fragment="{{shader_code}}" width="1000" height="1000"</canvas>
<!-- Displays shader -->
<script>
var canvas = document.createElement("canvas");
document.getElementById("shader-container").appendChild(canvas);
canvas.setAttribute("width", "1000");
canvas.setAttribute("height", "1000")
var sandbox = new GlslCanvas(canvas);
sandbox.load("{{shader_code}}");
</script>
</div>
Django-Backend:
from django.http import HttpResponse
from django.shortcuts import render
def shaders_view(request, *args, **kwargs) -> HttpResponse:
shader_code = read_shader_code()
context = {"shader_code": shader_code}
return render(request, 'shaders.html', context)
def read_shader_code():
with open("shaders\shader.frag", "r") as f:
return f.read().replace("\n", "\\n").replace("\t","\\t")