I'm working on implementing a directional linear gradient shader in Three js. It's my first time working with shaders, but I have a starting point here:
uniforms: {
color1: {
value: new Three.Color('red')
},
color2: {
value: new Three.Color('purple')
},
bboxMin: {
value: geometry.boundingBox.min
},
bboxMax: {
value: geometry.boundingBox.max
}
},
vertexShader: `
uniform vec3 bboxMin;
uniform vec3 bboxMax;
varying vec2 vUv;
void main() {
vUv.y = (position.y - bboxMin.y) / (bboxMax.y - bboxMin.y);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
}
`,
fragmentShader: `
uniform vec3 color1;
uniform vec3 color2;
varying vec2 vUv;
void main() {
gl_FragColor = vec4(mix(color1, color2, vUv.y), 1.0);
}
`,
this works great for a 'bottom up' linear gradien where color1 (red) is on the bottom and color2(purple) is on the top. I'm trying to figure out how to rotate the direction the gradient is going in. I know it requires editing the void main() {
function, however I'm a bit lost as to the needed math.
Basically i'm trying to reimplement svg gradient definitions:
viewBox="0 0 115.23 322.27">
<defs>
<linearGradient id="linear-gradient" x1="115.95" y1="302.98" x2="76.08" y2="143.47" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#8e0000"/>
<stop offset="1" stop-color="#42210b"/>
</linearGradient>
So I have to turn the viewbox, and x1,y1,x2,y2, and the possibility for more than two "stop" colors into uniforms and some kinda logic that works