文章目录
- 思路
- 传递 uv
- 传递 `position`
- 限制渐变范围
- 指定渐变颜色
思路
vertexShader
中使用varying
定义的变量可以在fragmentShader
中使用
传递 uv
const vertexShader = `varying vec2 v_uv;void main () {v_uv = uv;gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);}
`;const fragmentShader = `varying vec2 v_uv;void main () {gl_FragColor = vec4(v_uv,0.7,1);}
`;export const colorPlaneShader = {vertexShader,fragmentShader,
};

const colorBox = () => {const box = new THREE.Mesh(new THREE.BoxGeometry(5, 6, 10),new THREE.ShaderMaterial({...colorUVShader,}));box.translateX(10);return box;
};
传递 position
const veryingPositionShader = {vertexShader: `varying vec3 v_position;void main () {v_position = position;gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);}`,fragmentShader: ` varying vec3 v_position;void main () {gl_FragColor = vec4(v_position,1);}`,
};

限制渐变范围

const appointColorBox = () => {const vertexShader = `varying vec3 v_position;void main () {v_position = position;gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);}`;const fragmentShader = `varying vec3 v_position;// 最小颜色值float min = 0.6835559;// 最大颜色值float max = 0.6255737;void main () {// 无法直接修改 v_position// 限制在这个区间float val = min + (max - min) * v_position.y;gl_FragColor = vec4(val,val,val,1);}`;const box = new THREE.Mesh(new THREE.BoxGeometry(5, 6, 10),new THREE.ShaderMaterial({vertexShader,fragmentShader,side: 2,}));return box;
};
指定渐变颜色

lineGradientSphere({ r: 1, g: 0, b: 0 }, { r: 1, g: 1, b: 1 })
export const lineGradientSphere = (color1: { r: number; g: number; b: number },color2: { r: number; g: number; b: number }
) => {const vertexShader = `varying vec2 v_uv;void main () {v_uv = uv;gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);}`;const fragmentShader = `varying vec2 v_uv;uniform float u_r_base;uniform float u_g_base;uniform float u_b_base;uniform float u_r_space;uniform float u_g_space;uniform float u_b_space;void main () {// 限制在这个区间float r = u_r_base + (u_r_space) * v_uv.y;float g = u_g_base + (u_g_space) * v_uv.y;float b = u_b_base + (u_b_space) * v_uv.y;gl_FragColor = vec4(abs(r),abs(g),abs(b),1);}`;const uniforms = {u_r_base: { value: color1.r },u_g_base: { value: color1.g },u_b_base: { value: color1.b },u_r_space: {value: color1.r - color2.r,},u_g_space: {value: color1.g - color2.g,},u_b_space: {value: color1.b - color2.b,},};const sphere = new THREE.Mesh(new THREE.SphereGeometry(3.14, 32, 32),new THREE.ShaderMaterial({vertexShader,fragmentShader,side: 2,uniforms,}));return sphere;
};