threejs shader
时间: 2023-08-24 19:09:45 浏览: 66
Three.js is a JavaScript library used for creating 3D graphics in the browser. It provides a set of built-in shaders that can be used to create various visual effects like reflections, refractions, shadows, and more. Three.js shaders are written in GLSL (OpenGL Shading Language), a C-like language used for programming graphics processing units (GPUs).
To create a custom shader in Three.js, you need to define a new shader material and pass in the GLSL code as a string. Here is an example of a simple custom shader that applies a color gradient based on the object's Y position:
```
var customShader = new THREE.ShaderMaterial({
uniforms: {
color1: { value: new THREE.Color(0xff0000) },
color2: { value: new THREE.Color(0x0000ff) }
},
vertexShader: `
varying vec3 vPosition;
void main() {
vPosition = position;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 color1;
uniform vec3 color2;
varying vec3 vPosition;
void main() {
float t = (vPosition.y + 1.0) / 2.0;
gl_FragColor = vec4(mix(color1, color2, t), 1.0);
}
`
});
var cube = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
customShader
);
scene.add(cube);
```
This shader defines two uniforms (color1 and color2) that represent the two colors of the gradient. In the vertex shader, we pass the vertex position to the fragment shader via a varying variable. In the fragment shader, we calculate the gradient value (t) based on the Y position of the vertex and use the mix() function to interpolate between the two colors. Finally, we set the output color using gl_FragColor.