1. 程式人生 > >threejs的shader材質 顏色混合函式mix

threejs的shader材質 顏色混合函式mix

float mix(floatx,float y,float a ) 返回x和y 的線性混合,即x(1-a)+ya

three.js webgl - shader [Monjori]
	<div id="container"></div>
	<script src="js/three.js"></script>

	<script src="js/Detector.js"></script>

	<script id="vertexShader" type="x-shader/x-vertex">
		varying vec2 vUv;

		void main()
		{
			vUv = uv;
			vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
			gl_Position = projectionMatrix * mvPosition;
		}
	</script>

	<script id="fragmentShader" type="x-shader/x-fragment">
		uniform float time;
        uniform bool  isoriginColor;
		uniform sampler2D texture3;
		uniform sampler2D texture4;
		varying vec2 vUv;

		void main( void ) {
			vec2 position = - 1.0 + 2.0 * vUv;
			vec4 color3 = texture2D( texture3, vUv );
			vec3 tarcolor =color3.rgb;
			float f1 =color3.a;
			vec4 color4 = texture2D( texture4, vUv );
			float f2 =color4.a;
			if(isoriginColor == false){
				tarcolor =mix(tarcolor.rgb,color4.rgb,f2);
			}
			gl_FragColor = vec4(tarcolor,1);
		}
	</script>

	<script>
		if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
		var container;
		var camera, scene, renderer;
		var uniforms;
		init();
		animate();
		function init() {
			container = document.getElementById( 'container' );
			camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
			scene = new THREE.Scene();
			var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
			var textureLoader = new THREE.TextureLoader();
			uniforms = {
				time: { value: 1.0 },
				texture3:{value:textureLoader.load("time1.jpg" )},
				texture4:{value:textureLoader.load("2.png" )}
			};
			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 );
			onWindowResize();
			window.addEventListener( 'resize', onWindowResize, false );
		}
		function onWindowResize( event ) {
			renderer.setSize( window.innerWidth, window.innerHeight );
		}
		//
		function animate( timestamp ) {
			requestAnimationFrame( animate );
			uniforms.time.value = timestamp / 1000;
			renderer.render( scene, camera );
		}
	</script>

</body>
```![在這裡插入圖片描述](https://img-blog.csdn.net/20181017153331250?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JhbnJhbjEyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)

在這裡插入圖片描述在這裡插入圖片描述在這裡插入程式碼片

gl_FragColor = vec4(tarcolor.rgb+color4.rgb,1);

在這裡插入圖片描述

1 2 gl_FragColor = vec4(tarcolor.rgb-color4.rgb,1);

![在這裡插入圖片描述](https://img-blog.csdn.net/20181017155017578?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3JhbnJhbjEyNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)