Simple Shader with ThreeJS

Ok folks, it doesn’t get easier than this. If you want to start writing shaders in the browser but can’t figure out how to create your shader program, ThreeJS has you covered:

In your JS

var camera = new THREE.Camera();
	camera.position.z = 1;

	var scene = new THREE.Scene();

	var uniforms = {
		time: { type: "f", value: 1.0 },
		resolution: { type: "v2", value: new THREE.Vector2() }
	};

	var material = new THREE.ShaderMaterial( {
		uniforms: uniforms,
		vertexShader: document.getElementById( 'vertexShader' ).innerText,
		fragmentShader: document.getElementById( 'fragmentShader' ).innerText
	});

	var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), material );

	scene.add( mesh );

	var canvas = document.querySelector(".lense-flare");
	var parent = canvas.parentElement;
	var renderer = new THREE.WebGLRenderer({ canvas: canvas });
	renderer.setSize( parent.clientWidth, parent.clientHeight );

	uniforms.resolution.value.x = parent.clientWidth;
	uniforms.resolution.value.y = parent.clientHeight;
	var startTime = Date.now();

	animate();

	function animate() {
		requestAnimationFrame( animate );
		render();
	}

	function render() {
		var elapsedMilliseconds = Date.now() - startTime;
		var elapsedSeconds = elapsedMilliseconds / 1000.;
		uniforms.time.value = 60. * elapsedSeconds;
		renderer.render( scene, camera );
	}

 

In your head:

<script id="vertexShader" type="x-shader/x-vertex">
			uniform float time;
			uniform vec2 resolution;
			void main()	{
				gl_Position = vec4( position, 1.0 );
			}
		</script>
		<script id="fragmentShader" type="x-shader/x-fragment">
			uniform float time;
			uniform vec2 resolution;
			void main()	{
				float x = mod(time + gl_FragCoord.x, 20.) < 10. ? 1. : 0.;
				float y = mod(time + gl_FragCoord.y, 20.) < 10. ? 1. : 0.;
				gl_FragColor = vec4(vec3(min(x, y)), 1.);
			}
		</script>

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *