skip to Main Content

I am just starting with Next.js I have been trying to access the web cam for a project I have been working on but I have found an issue when it comes to writing in the "script" tag

Here is the simple code for page.js

export default function Live(){
return(
    <html>
        <body>
            <video id="webCam" autoPlay width="600" height="600"></video>
            <a download>Take Picture</a>
            <script src="myscript.js" />
        </body>
    </html>
);
}

Here is the code for the "myscript.js" file

console.log("in")
const webCamEle = document.getElementByID("webCam");
navigator.mediaDevices.getUserMedia({video: true}).then((stream)=> {
    webCamEle.srcObject = stream
}).catch((error) => {console.error(error)});

I don’t even get the console logs which leads me to believe that it’s not finding the file at all. Every video I have followed showed that I have been doing the right things and when I run the app, all I get is the button popping up. I’m hoping to get a live camera feed to pop up eventually but now I just want to know that the "myscript.js" file is being read.

2

Answers


  1. 1.serve static files like myscript.js, place them in the public directory of your Next.js project,try this and see if it helps.
    2. tag should be used with the next/script module for better integration. However, since your script is external, you should make sure that it’s loaded correctly.
    If it does not work,ping me ,will delve deep into this

    Login or Signup to reply.
  2. You need to use component structure, create a component MyWebcam.js:

    "use client";
    
    import { useEffect, useRef } from 'react';
    
    const MyWebcam = () => {
        const videoRef = useRef(null);
    
      useEffect(() => {
        const getUserMedia = async () => {
          try {
            const stream = await navigator.mediaDevices.getUserMedia({ video: true });
            if (videoRef.current) {
              videoRef.current.srcObject = stream;
            }
          } catch (error) {
            console.error(error);
          }
        };
    
        getUserMedia();
      }, []);
    
      return (
        <div>
          <video ref={videoRef} autoPlay width="600" height="600"></video>
          <a download>Take Picture</a>
        </div>
      );
    };
    
    export default MyWebcam;
    

    page.js

    import MyWebcam from "@/components/MyWebcam";
    export default function Live(){
    return(
        <html>
            <body>
                <MyWebcam />
            </body>
        </html>
    );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search