Luke's Studio

Published

- 2 min read

Passing Uniforms to Shaders

Shaders and GLSL

I’m currently learning how to create shaders in WebGL using GLSL. I’m taking the wonderful Three Js Journey course, which I could not recommend enough! And also reading the Book of shaders.

Colours

Time Uniform

Using the u_time uniform we can change the FragColor red value dependent on time as a sin wave:

   #ifdef GL_ES
precision mediump float;
#endif

uniform float u_time;

void main() {
    gl_FragColor = vec4(sin(u_time), 0.0, 0.0, 1.0);
}

Resolution Uniform

Using the u_resolution we can calculate where the pixel is on the canvas by dividing the x and y position (FragCoord) by the resolution.

Add st.x as the red value will make it go from 0 to 1 and same for the y on the green value.

Which means the further right on the canvas will be more red and the further towards the top will go green.

   #ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

void main() {
	vec2 st = gl_FragCoord.xy/u_resolution;
	gl_FragColor = vec4(st.x,st.y,0.0, 1.0);
}

Mouse uniform

Combining the resolution and mouse uniform means we can track where the users mouse is on the shader and can manipulate what colour is shown.

Here we need to get the mouse position which is a vec2 by dividing it by the resolution of the current canvas. From there we can use distance to mouse to manipulate the color.

   #ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;

void main() {
    vec2 mousePos = u_mouse / u_resolution;
    vec2 st = gl_FragCoord.xy / u_resolution;
    float distToMouse = distance(st, mousePos);
    vec3 color = vec3(1.0 - distToMouse);
    gl_FragColor = vec4(color, 1.0);
}

All uniforms together

Let’s use all the uniforms, time, resolution and mouse to create some art!

I will use sin with u_time for the red colour. I will use the position of the u_mouse distance on the canvas which will be for green and then the gradient of blue using left to ring x.

   #ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;

void main() {
    vec2 mousePos = u_mouse / u_resolution;
    vec2 st = gl_FragCoord.xy / u_resolution;
    float distToMouse = distance(st, mousePos);
    gl_FragColor = vec4(sin(u_time), 1.0 - distToMouse, st.x, 1.0);
}

Related Posts

There are no related posts yet. 😢
)