Threejs中的ShaderMaterial可以使用自定义的shader,参数vertexShader和fragmentShader分别对应顶点着色器和片段着色器的内容(由GLSL写成)。
顶点着色器和片段着色器的内容可以分别放到一个<script>标签内
<script id="vs" type="x-shader/x-vertex">
varying vec4 vPosition;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
vPosition = gl_Position;
}
</script>
<script id="fs" type="x-shader/x-fragment">
varying vec4 vPosition;
void main() {
gl_FragColor = vec4(vPosition.x+0.5,vPosition.y+0.5,vPosition.z+0.5,1.0);
}
</script>
然后可以通过下面的方式创建ShaderMaterial
var material = new THREE.ShaderMaterial( {
vertexShader: document.getElementById( 'vs' ).textContent.trim(),
fragmentShader: document.getElementById( 'fs' ).textContent.trim()
} );
将上面的材质赋予模型后,模型的顶点颜色与顶点的位置相关,完整代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>threejs custom shader</title>
</head>
<body>
<div id="container"/>
<script src="three.js"></script>
<script id="vs" type="x-shader/x-vertex">
varying vec4 vPosition;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
vPosition = gl_Position;
}
</script>
<script id="fs" type="x-shader/x-fragment">
varying vec4 vPosition;
void main() {
gl_FragColor = vec4(vPosition.x+0.5,vPosition.y+0.5,vPosition.z+0.5,1.0);
}
</script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(90,window.innerWidth/window.innerHeight,0.1,1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container = document.getElementById("container");
container.appendChild(renderer.domElement);
var geometry=new THREE.BoxGeometry(1,1,1);
var material = new THREE.ShaderMaterial( {
vertexShader: document.getElementById( 'vs' ).textContent.trim(),
fragmentShader: document.getElementById( 'fs' ).textContent.trim()
} );
var cube = new THREE.Mesh(geometry,material);
scene.add(cube);
camera.position.z=5;
var animate = function()
{
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene,camera);
};
animate();
</script>
</body>
</html>
该实例创建一个转动的立方体,各顶点处的颜色由该顶点的位置决定,运行后的效果
通过自定义shader可以实现各种复杂材质效果,而不局限于threejs已有的材质类型.
Copyright © 2021 .长沙麦涛网络科技有限公司 All rights reserved.
湘ICP备20015126号-2
联系我们