Skip to main content

Plug BadTVShader into React Three Fiber

10/7/20211 min read

I've been building a scene in R3f and wanted to pull in the awesome Bad TV Shader by Felix Turner and have it affect a video stream on a plane. It took me a while to figure this out so I'm going to write it down here.

import {VideoTexture } from "three";
import {useFrame} from 'react-three-fiber'

const TV = ({videoElement}) => {
  /* Create a ref to access the shader later*/
  const shaderRef = useRef();
   
  /* Update the shader's time uniform value every frame */
  useFrame(() => {
    if (shaderRef.current) {
      shaderRef.current.uniforms.time.value += 0.04;
    }
  });

  /* Create a ThreeJS Video Texture for a given preconfigured video element */
  const videoTexture = new VideoTexture(videoElement);

  return (
      <mesh>
        <planeGeometry args={[0.4, 0.3, 20, 1]} />
        <shaderMaterial
    	    /* Set shader ref */
            ref={shaderRef}
      		/* Pass the shader into the args array */
            args={[BadTVShader]}
            /* Attach ShaderMaterial to the mesh as a material */
            attach="material"
            /* Set the uniform value for tDiffuse to the video texture */
            uniforms-tDiffuse-value={videoTexture}
        />
      </mesh>
  );
};
Read moreBack
© 2021 by Madole.
GitHub Repository
Last build: 1713357749652