Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Write CRT-screen effect using curtains.js

  1. User

    Write CRT-screen effect using curtains.js

  2. Assistant

    Creating a CRT (Cathode Ray Tube) screen effect using Curtains.js involves leveraging WebGL shaders to simulate the visual characteristics of old CRT monitors, such as scanlines, curvature, chromatic aberration, and glow. Below is a comprehensive guide, complete with HTML, CSS, JavaScript, and GLSL shader code, to help you achieve this effect.

    Table of Contents

    1. Setup
    2. HTML Structure
    3. CSS Styling
    4. JavaScript with Curtains.js
    5. GLSL Shaders
    6. Complete Code Example

    Setup

    Before diving into the code, ensure you have the following:

    • A basic web development environment (HTML, CSS, JavaScript).
    • Curtains.js library included in your project. You can include it via CDN.

    HTML Structure

    We'll create a simple HTML structure with a canvas element where Curtains.js will render the effect.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>CRT Screen Effect with Curtains.js</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <div id="canvas"></div>
    
      <!-- Include Curtains.js via CDN -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/curtainsjs/9.1.9/curtains.min.js" integrity="sha512-VE1EujAbH4LOxsYP24LxLYbjm+QocVYlMkTSAmqGqRTz2amxvOynbV9YuU6yagw7Lk6WrAnqIoKaCygzT4vNcw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
      <!-- Include your custom script -->
      <script src="script.js"></script>
    </body>
    </html>
    

    CSS Styling

    We'll style the canvas to occupy the full viewport and ensure the rendered effect is centered.

    /* styles.css */
    
    body, html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      background-color: #000;
    }
    
    #canvas {
      width: 100%;
      height: 100%;
      position: relative;
    }
    

    JavaScript with Curtains.js

    This script initializes Curtains.js, creates a plane with a texture (image or video), and applies the CRT shader effect.

    // script.js
    
    // Wait for the DOM to load
    document.addEventListener("DOMContentLoaded", function () {
      // Initialize Curtains
      const curtains = new Curtains({
        container: "canvas",
        watchScroll: false,
        pixelRatio: Math.min(1.5, window.devicePixelRatio) // Limit pixel ratio for performance
      });
    
      // Handle errors
      curtains.onError(() => {
        console.error("Failed to initialize Curtains.js.");
      });
    
      // Vertex Shader
      const vertexShader = `
        precision mediump float;
    
        // Default attributes
        attribute vec3 POSITION;
        attribute vec2 TEXCOORD;
    
        // Default uniforms
        uniform mat4 projectionMatrix;
        uniform mat4 modelViewMatrix;
    
        // Varyings
        varying vec2 vTexCoord;
    
        void main() {
          gl_Position = projectionMatrix * modelViewMatrix * vec4(POSITION, 1.0);
          vTexCoord = TEXCOORD;
        }
      `;
    
      // Fragment Shader (CRT Effect)
      const fragmentShader = `
        precision mediump float;
    
        uniform sampler2D texture;
        uniform vec2 resolution;
        uniform float time;
    
        varying vec2 vTexCoord;
    
        // Function to simulate scanlines and curvature
        void main() {
          // Simulate screen curvature
          vec2 uv = vTexCoord;
          vec2 centered = uv - 0.5;
          float dist = length(centered);
          uv += (centered / dist) * 0.02;
    
          // Sample the texture
          vec3 color = texture2D(texture, uv).rgb;
    
          // Add scanlines
          float scanline = sin(uv.y * resolution.y * 1.5);
          color *= 1.0 - 0.1 * scanline;
    
          // Chromatic aberration
          float offset = 0.002;
          vec3 red = texture2D(texture, uv + vec2(offset, 0.0)).rbg;
          vec3 green = texture2D(texture, uv).rgb;
          vec3 blue = texture2D(texture, uv - vec2(offset, 0.0)).rgb;
          color = vec3(red.r, green.g, blue.b);
    
          // Vignette effect
          float vignette = smoothstep(0.8, 0.5, dist * 2.0);
          color *= vignette;
    
          gl_FragColor = vec4(color, 1.0);
        }
      `;
    
      // Create a plane with the shader and a sample image
      const plane = new Plane(
        curtains,
        {
          vertexShader,
          fragmentShader,
          geometry: {
            widthSegments: 16,
            heightSegments: 16
          },
          uniforms: {
            resolution: {
              name: "resolution",
              type: "2f",
              value: [window.innerWidth, window.innerHeight]
            },
            time: {
              name: "time",
              type: "1f",
              value: 0
            }
          }
        },
        {
          // Specify the image to use as a texture
          vertexElement: null, // Not using DOM element
          texturesOptions: {
            sampler: "diffuse",
            // You can use any image URL or data URI
            // For demonstration, using a placeholder image
            url: "https://picsum.photos/1920/1080"
          }
        }
      );
    
      // Error handling for plane
      plane.onError(() => {
        console.error("Failed to create the plane.");
      });
    
      // Update uniform time on each render
      curtains.onRender(() => {
        plane.uniforms.time.value += 0.05;
      });
    
      // Handle window resize
      window.addEventListener("resize", () => {
        plane.uniforms.resolution.value = [
          window.innerWidth,
          window.innerHeight
        ];
      });
    });
    

    GLSL Shaders

    Shaders are programs that run on the GPU to process vertices and pixels. For the CRT effect, we'll use both vertex and fragment shaders.

    Vertex Shader

    The vertex shader handles the position of each vertex. In this case, it's a standard shader passing texture coordinates to the fragment shader.

    // vertexShader in script.js
    
    precision mediump float;
    
    // Default attributes
    attribute vec3 POSITION;
    attribute vec2 TEXCOORD;
    
    // Default uniforms
    uniform mat4 projectionMatrix;
    uniform mat4 modelViewMatrix;
    
    // Varyings
    varying vec2 vTexCoord;
    
    void main() {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(POSITION, 1.0);
      vTexCoord = TEXCOORD;
    }
    

    Fragment Shader

    The fragment shader applies the CRT effect by simulating scanlines, screen curvature, chromatic aberration, and a vignette.

    // fragmentShader in script.js
    
    precision mediump float;
    
    uniform sampler2D texture;
    uniform vec2 resolution;
    uniform float time;
    
    varying vec2 vTexCoord;
    
    // Function to simulate scanlines and curvature
    void main() {
      // Simulate screen curvature
      vec2 uv = vTexCoord;
      vec2 centered = uv - 0.5;
      float dist = length(centered);
      uv += (centered / dist) * 0.02;
    
      // Sample the texture
      vec3 color = texture2D(texture, uv).rgb;
    
      // Add scanlines
      float scanline = sin(uv.y * resolution.y * 1.5);
      color *= 1.0 - 0.1 * scanline;
    
      // Chromatic aberration
      float offset = 0.002;
      vec3 red = texture2D(texture, uv + vec2(offset, 0.0)).rbg;
      vec3 green = texture2D(texture, uv).rgb;
      vec3 blue = texture2D(texture, uv - vec2(offset, 0.0)).rgb;
      color = vec3(red.r, green.g, blue.b);
    
      // Vignette effect
      float vignette = smoothstep(0.8, 0.5, dist * 2.0);
      color *= vignette;
    
      gl_FragColor = vec4(color, 1.0);
    }
    

    Shader Breakdown:

    1. Screen Curvature:

      • Distorts the UV coordinates to simulate the curved glass of a CRT monitor.
    2. Scanlines:

      • Adds horizontal lines to mimic the scanlines seen on old displays.
    3. Chromatic Aberration:

      • Offsets the red and blue channels slightly to create a color separation effect.
    4. Vignette:

      • Darkens the edges of the screen to draw focus to the center.

    Complete Code Example

    For your convenience, here's the complete code assembled together.

    HTML (index.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>CRT Screen Effect with Curtains.js</title>
      <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <div id="canvas"></div>
    
      <!-- Include Curtains.js via CDN -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/curtainsjs/9.1.9/curtains.min.js" integrity="sha512-VE1EujAbH4LOxsYP24LxLYbjm+QocVYlMkTSAmqGqRTz2amxvOynbV9YuU6yagw7Lk6WrAnqIoKaCygzT4vNcw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
      <!-- Include your custom script -->
      <script src="script.js"></script>
    </body>
    </html>
    

    CSS (styles.css)

    body, html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      background-color: #000;
    }
    
    #canvas {
      width: 100%;
      height: 100%;
      position: relative;
    }
    

    JavaScript (script.js)

    // script.js
    
    // Wait for the DOM to load
    document.addEventListener("DOMContentLoaded", function () {
      // Initialize Curtains
      const curtains = new Curtains({
        container: "canvas",
        watchScroll: false,
        pixelRatio: Math.min(1.5, window.devicePixelRatio) // Limit pixel ratio for performance
      });
    
      // Handle errors
      curtains.onError(() => {
        console.error("Failed to initialize Curtains.js.");
      });
    
      // Vertex Shader
      const vertexShader = `
        precision mediump float;
    
        // Default attributes
        attribute vec3 POSITION;
        attribute vec2 TEXCOORD;
    
        // Default uniforms
        uniform mat4 projectionMatrix;
        uniform mat4 modelViewMatrix;
    
        // Varyings
        varying vec2 vTexCoord;
    
        void main() {
          gl_Position = projectionMatrix * modelViewMatrix * vec4(POSITION, 1.0);
          vTexCoord = TEXCOORD;
        }
      `;
    
      // Fragment Shader (CRT Effect)
      const fragmentShader = `
        precision mediump float;
    
        uniform sampler2D texture;
        uniform vec2 resolution;
        uniform float time;
    
        varying vec2 vTexCoord;
    
        // Function to simulate scanlines and curvature
        void main() {
          // Simulate screen curvature
          vec2 uv = vTexCoord;
          vec2 centered = uv - 0.5;
          float dist = length(centered);
          uv += (centered / dist) * 0.02;
    
          // Sample the texture
          vec3 color = texture2D(texture, uv).rgb;
    
          // Add scanlines
          float scanline = sin(uv.y * resolution.y * 1.5);
          color *= 1.0 - 0.1 * scanline;
    
          // Chromatic aberration
          float offset = 0.002;
          vec3 red = texture2D(texture, uv + vec2(offset, 0.0)).rbg;
          vec3 green = texture2D(texture, uv).rgb;
          vec3 blue = texture2D(texture, uv - vec2(offset, 0.0)).rgb;
          color = vec3(red.r, green.g, blue.b);
    
          // Vignette effect
          float vignette = smoothstep(0.8, 0.5, dist * 2.0);
          color *= vignette;
    
          gl_FragColor = vec4(color, 1.0);
        }
      `;
    
      // Create a plane with the shader and a sample image
      const plane = new Plane(
        curtains,
        {
          vertexShader,
          fragmentShader,
          geometry: {
            widthSegments: 16,
            heightSegments: 16
          },
          uniforms: {
            resolution: {
              name: "resolution",
              type: "2f",
              value: [window.innerWidth, window.innerHeight]
            },
            time: {
              name: "time",
              type: "1f",
              value: 0
            }
          }
        },
        {
          // Specify the image to use as a texture
          vertexElement: null, // Not using DOM element
          texturesOptions: {
            sampler: "diffuse",
            // You can use any image URL or data URI
            // For demonstration, using a placeholder image
            url: "https://picsum.photos/1920/1080"
          }
        }
      );
    
      // Error handling for plane
      plane.onError(() => {
        console.error("Failed to create the plane.");
      });
    
      // Update uniform time on each render
      curtains.onRender(() => {
        plane.uniforms.time.value += 0.05;
      });
    
      // Handle window resize
      window.addEventListener("resize", () => {
        plane.uniforms.resolution.value = [
          window.innerWidth,
          window.innerHeight
        ];
      });
    });
    

    Customizing the Effect

    Feel free to tweak the shader parameters to better suit your aesthetic preferences:

    • Scanlines:

      • Adjust the frequency and intensity by modifying the sin function and multiplier in the scanline calculation.
    • Curvature:

      • Change the curvature effect by altering the uv distortion values.
    • Chromatic Aberration:

      • Modify the offset value to increase or decrease the color separation.
    • Vignette:

      • Adjust the smoothstep parameters to control the strength and spread of the vignette.

    Using a Video Instead of an Image

    If you'd like to apply the CRT effect to a video instead of a static image, you can modify the texture setup in the JavaScript code.

    1. HTML:
      • Add a video element.
    <video id="video" src="path_to_your_video.mp4" crossorigin="anonymous" loop muted playsinline></video>
    
    1. JavaScript:
      • Use the video as the texture source.
    const video = document.getElementById("video");
    video.play();
    
    const plane = new Plane(
      curtains,
      {
        // ... (same as before)
      },
      {
        vertexElement: null,
        texturesOptions: {
          sampler: "diffuse",
          video: video // Use the video element
        }
      }
    );
    

    Ensure the video is properly loaded and has the appropriate CORS settings if hosted externally.

    Conclusion

    By following the steps above, you can create a visually appealing CRT screen effect using Curtains.js. This effect can enhance various web projects, such as retro-themed websites, art portfolios, or interactive media. Remember to experiment with different shader parameters to achieve the desired look and feel.

    Feel free to reach out if you have any questions or need further assistance!