Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a time uniform in webgl

Tags:

webgl

I am new to webgl. I am trying to set a time uniform, so I can change the output of my fragment shader as time passes. I thought this would be fairly simple to implement but I am struggling. I am aware that these two methods are probably involved:

  • https://developer.mozilla.org/en-US/docs/Web/API/WebGLUniformLocation

  • https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniform

Is some kind of rendering loop required?

Any help here would be really appreciated, thanks.

like image 264
alexLMS Avatar asked Jul 16 '17 18:07

alexLMS


1 Answers

This is my current solution...

In my webgl JS file I create a time uniform, then set it every animation frame with an updated value.

// create time uniform
var timeLocation = context.getUniformLocation(program, "u_time"); 

function renderLoop(timeStamp) { 

  // set time uniform
  gl.uniform1f(timeLocation, timeStamp/1000.0);

  gl.drawArrays(...);

  // recursive invocation
  window.requestAnimationFrame(renderLoop);
}

// start the loop
window.requestAnimationFrame(renderLoop);

Then in my fragment shader:

precision mediump float;

uniform float u_time;

void main() {
   gl_FragColor = vec4(abs(sin(u_time)),0.0,0.0,1.0);
}
like image 172
alexLMS Avatar answered Oct 19 '22 21:10

alexLMS