Objects disappear after adding a gradient

Hello, I am interested in learning three.js, trying to do my first project, I am trying to apply a gradient behind 3d meshes, could you please explain why they disappear when a gradient is added to the scene

When I try to add it to the scene

    let p = new THREE.Mesh(g, m);
    p.position.set(0, 0, -1);
   scene.add(p);

the cube and sphere disappear, can you suggest a solution and topics to read, thanks

full code

function MyThree() {
  const refContainer = useRef(null);

  useEffect(() => {
    // === THREE.JS CODE START ===
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);

    // Append renderer to the ref container
    refContainer.current && refContainer.current.appendChild(renderer.domElement);
    
    let g = new THREE.PlaneGeometry(2, 2);
    let m = new THREE.ShaderMaterial({
        uniforms: {
          color1: { value: new THREE.Color(0x5a636a)},
          color2: { value: new THREE.Color(0x111822)},
          ratio: {value: 500 / 500}
        },
        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. );
            }`
        })
   
    // === Create Gradient Background ===
    // const createGradientTexture = () => {
    //   const canvas = document.createElement('canvas');
    //   const context = canvas.getContext('2d');

    //   // Set canvas size
    //   canvas.width = 512;
    //   canvas.height = 512;

    //   // Create gradient
    //   const gradient = context.createLinearGradient(0, 0, 0, canvas.height);
    //   // gradient.addColorStop(0, '#0D1112'); // Top color
    //   gradient.addColorStop(0, '#000000'); // Top color
    //   gradient.addColorStop(1, '#0D1112'); // Bottom color

    //   // Apply gradient to canvas
    //   context.fillStyle = gradient;
    //   context.fillRect(0, 0, canvas.width, canvas.height);

    //   // Use canvas as texture
    //   const texture = new THREE.CanvasTexture(canvas);
    //   return texture;
    // };

    // const gradientTexture = createGradientTexture();
    // scene.background = gradientTexture;

    // === LIGHT ===
    const amb = new THREE.AmbientLight(0xffffff, 0.5);
    scene.add(amb);

    const pointLight = new THREE.PointLight(0xffffff, 0.5);
    pointLight.position.set(5, 5, 5);
    scene.add(pointLight);

    const SphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
    var geometry = new THREE.BoxGeometry(4, 2, 2);
    var material = new THREE.MeshBasicMaterial({ color: 0x808080 });

    const sphere = new THREE.Mesh(SphereGeometry, material);
    scene.add(sphere);

    sphere.position.x = 0.1;
    sphere.position.y = 2.1;
    sphere.position.z = 1.7;


     // ============ < CUBE > =============== 

    var cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    cube.rotation.x = 1.3;
    cube.rotation.y = 3.1;
    cube.rotation.z = 2.8;

    cube.position.x = 1.1;
    cube.position.y = -0.1;
    cube.position.z = 1.7;

    camera.position.set(10, 10, 0); // Move the camera back and down to see the plane
    camera.lookAt(0, 0, 0); 

    // Background gradient
    let p = new THREE.Mesh(g, m);
    p.position.set(0, 0, -1);
    scene.add(p);

    // Create text using Canvas
    const createTextSprite = (message, opts = {}) => {
      const { fontSize = 50, color = 'white' } = opts;

      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      context.font = `${fontSize}px Arial`;
      context.fillStyle = color;
      context.fillText(message, 0, fontSize);

      const texture = new THREE.CanvasTexture(canvas);
      const material = new THREE.MeshStandardMaterial({ map: texture });
      material.roughness = 0.4;

      const sprite = new THREE.Sprite(material);
      sprite.scale.set(3, 1.5, 1);

      return sprite;
    };

    const textSprite = createTextSprite('blue', { fontSize: 40, color: 'white' });
    textSprite.position.set(-5, 2.5, 0); 
    scene.add(textSprite);

    var animate = function () {
      requestAnimationFrame(animate);
      cube.rotation.x += 0.001;
      renderer.render(scene, camera);
    };
    animate();

    // Handle window resize
    const handleResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return <div ref={refContainer}></div>;
}

If you use custom shaders and objects disappear- in 99% cases it means the shader code is invalid. Check browser devtools console and see if there’s any errors there.

1 Like