To create a sine gradient effect, you'll require 2 uniform variables in your vertex shader: the resolution of the viewport (u_resolution
) and the time (u_time
) in seconds:
uniform vec2 u_resolution;
uniform float u_time;
The x value can be obtained by the x coordinate of the fragment. Map the x coordinate to the range [0, 2*PI]:
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float x = st.x * 2.0 * 3.141529;
Next, calculate the value of y
. Utilize the sin
function which represents the Sine value:
float y = sin(x + u_time);
Assign the color channels of the fragment based on the value of y
. Ensure that y
is mapped from the range [-1, 1] to [0, 1]:
gl_FragColor = vec4(vec3(y*0.5+0.5), 1.0);
The end result will be a visually appealing sine gradient that moves from right to left:
var container, camera, scene, renderer, uniforms;
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.Camera();
camera.position.z = 1;
scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
uniforms = {
u_time: { type: "f", value: 1.0 },
u_resolution: { type: "v2", value: new THREE.Vector2() }
};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
container.appendChild( renderer.domElement );
(window.onresize = function() {
renderer.setSize( window.innerWidth, window.innerHeight );
uniforms.u_resolution.value.x = renderer.domElement.width;
uniforms.u_resolution.value.y = renderer.domElement.height;
})();
}
function animate(delta_ms) {
requestAnimationFrame( animate );
uniforms.u_time.value = delta_ms / 1000.0;
renderer.render( scene, camera );
}
<script id="vertexShader" type="x-shader/x-vertex">
void main() {
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
uniform vec2 u_resolution;
uniform float u_time;
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float x = st.x * 2.0 * 3.141529;
float y = sin(x + u_time);
gl_FragColor = vec4(vec3(y*0.5+0.5), 1.0);
}
</script>
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>