Radial Gradient shader for the scene background

I am trying to create a radial gradient background for my scene. I’ve found that two of my options are:
a) setting it up with CSS using ‘canvas.style.background’, but this won’t be reflected on the objects in the scene.
b) creating a plane with a custom shader material

After a lot of figuring out what any of that means, I’ve managed to find a gradient material shader that somewhat works, but isn’t radial. How can I make it radial as opposed to linear?
Also, is it possible to create a radial gradient with “scene.background”?

var material = new THREE.ShaderMaterial({
    uniforms: {
      color1: { value: new THREE.Color(`hsl(200, 40%, 70%)`)},
      color2: { value: new THREE.Color(`hsl(110, 40%, 70%)`)}
    },
    vertexShader: `varying vec2 vUv;
      void main(){
        vUv = uv;
        float depth = 1.;
        gl_Position = vec4(position.xy, depth, 1.);
      }`,
          fragmentShader: `varying vec2 vUv;
        uniform vec3 color1;
        uniform vec3 color2;
        void main(){
          gl_FragColor = vec4( mix( color1, color2, vec3(vUv.y)), 1. );
        }`
    })

You need the ratio of screen width and height, that you pass in a uniform.
Then, in shaders, radial gradient depends on the length of UV coordinate. https://jsfiddle.net/prisoner849/xqpwk7e0/

let m = new THREE.ShaderMaterial({
    uniforms: {
      color1: { value: new THREE.Color(0xff00ff)},
      color2: { value: new THREE.Color(0xff0000)},
      ratio: {value: innerWidth / innerHeight}
    },
    vertexShader: `varying vec2 vUv;
      void main(){
        vUv = uv;
        gl_Position = vec4(position, 1.);
      }`,
          fragmentShader: `varying vec2 vUv;
        uniform vec3 color1;
        uniform vec3 color2;
        uniform float ratio;
        void main(){
        	vec2 uv = (vUv - 0.5) * vec2(ratio, 1.);
          gl_FragColor = vec4( mix( color1, color2, length(uv)), 1. );
        }`
    })

PS Not the ultimate solution, just a concept.

1 Like

I really like this solution. It’s exactly what I had in mind. Thank you very much!