locked
navigator.getUserMedia storing black photo RRS feed

  • Question

  • User-471420332 posted

    I am working on capturing photo on snap button click but getting Uncaught TypeError: Cannot read property 'addEventListener' of null error when i press f12 and storing storing black sreen in my photo folder.

    Below is my design code

      <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div>
                    <video id="video" width="320" height="240" autoplay></video>
                     <canvas id="canvas" width="320" height="240"></canvas>
                        <label id="lbltipAddedComment" ></label>
                </div>
                <!-- Modal body -->
                <div class="modal-body text-center">
    
                    Are you sure you want to submit this form?
                </div>
                <!-- Modal footer -->
                <div class="text-center d-block m-auto pb-4">
    
                    <button id="snap"  runat="server" class="starttest-btn"   >Snap</button>
    
                </div>

    below is my camera scripts

            <script type="text/javascript">
    
        /// $(document).bind("keydown", disableF5);
    
        var video = document.getElementById('video');
    
        // Get access to the camera!
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            //   Not adding `{ audio: true }` since we only want video now
            //navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
            //    video.src = window.URL.createObjectURL(stream);
            //    video.play();
            //});
    
            navigator.mediaDevices.getUserMedia({
                video: true
            })
          .then(function (stream) {
           video.srcObject = stream;
           })
          .catch(function (error) {
      //console.log('error', error);
     //  alert(error);
    // document.getElementById('lbltipAddedComment').innerHTML = error;
     document.getElementById('lbltipAddedComment').innerHTML = "Camera is not found, do want to continue your test without camera?";
    
        });
    
        }
        else if (navigator.getUserMedia) { // Standard
            navigator.getUserMedia({ video: true }, function (stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia({ video: true }, function (stream) {
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if (navigator.mozGetUserMedia) { // Mozilla-prefixed
            navigator.mozGetUserMedia({ video: true }, function (stream) {
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var video = document.getElementById('video');
    
        // Trigger photo take on load
       document.getElementById("snap").addEventListener("click", function () {
            // context.drawImage(video, 0, 0, 640, 480);
            context.drawImage(video, 0, 0, 320, 240);
        });
    </script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    
    <!--saving into db --->
    <script type="text/javascript">
        $(function () {
    
            $("[id*=snap]").bind("click", function () {
    
              //  context.drawImage(video, 0, 0, 320, 240);
                var image = document.getElementById("canvas").toDataURL("image/png");
    
                //get raw image data
                image = image.replace('data:image/png;base64,', '');
                          // alert(image);
    
                $.ajax({
                    type: "POST",
                    url: "stafffeedback.aspx/SaveUser",
                    data: '{"imageData": "' + image + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
    
    
                         alert("User snap has been added successfully.");
                        //   window.location.reload();
    
                    },
                    error: function (jqXHR, exception) {
                        var msg = '';
                        if (jqXHR.status === 0) {
                            // msg = 'Not connect.\n Verify Network.';
                            alert("Not connect.\n Verify Network..");
                        } else if (jqXHR.status == 404) {
                            //   msg = 'Requested page not found. [404]';
                            alert("Requested page not found. [404].");
                        } else if (jqXHR.status == 500) {
                            //  msg = 'Internal Server Error [500].';
                            alert("Internal Server Error [500].");
                        } else if (exception === 'parsererror') {
                            //   msg = 'Requested JSON parse failed.';
                            alert("Requested JSON parse failed.");
                        } else if (exception === 'timeout') {
                            // msg = 'Time out error.';
                            alert("Time out error.");
                        } else if (exception === 'abort') {
                            //  msg = 'Ajax request aborted.';
                            alert("Ajax request aborted.");
                        } else {
                            // msg = 'Uncaught Error.\n' + jqXHR.responseText;
                            alert("Uncaught Error.\n." + jqXHR.responseText);
                        }
                        // $('#post').html(msg);
                    },
    
                });
                return false;
            });
        });
    
    
    
    
    
    </script>

    Below is my code behind c# code for storing image using web method

     static string path = @"F:\D Drive\current live projects\xyz\Users Photo\";
    
    //[WebMethod()] Session["Username"]
    [WebMethod(EnableSession = true)]
    public static void SaveUser(string imageData)
    {
        String photoTime = DateTime.Now.ToString("yyyy-MM-dd, HH.mm.ss");
        //Create image to local machine.
        string fileNameWitPath = path + photoTime + "_" + HttpContext.Current.Session["Username"] + ".png";
    
        string photofilename = photoTime + "_" + HttpContext.Current.Session["Username"] + ".png";
        using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
        {
    
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
    
                byte[] data = Convert.FromBase64String(imageData);
    
                bw.Write(data);
    
                bw.Close();
            }
    
        }
        // Save fileNameWitPath variable to Database.
    
        try
        {
           // Insert_CapturedImage(HttpContext.Current.Session["LoginId"].ToString(), photofilename);
        }
        catch (Exception ex)
        {
            // throw ex;
        }
    
    }

    When i Click on snap button then storing photo blank and i am trying this but not getting any solution to solve this issue also when press f12 showing that Uncaught TypeError: Cannot read property 'addEventListener

    Tuesday, July 16, 2019 8:22 AM

All replies

  • User753101303 posted

    Hi,

    So it seems 

    document.getElementById("snap")

    is null. More likely your script runs before the DOM is fully loaded because this block of script is not inside  $(function() - you have done this correctly for the other script block.

    Tuesday, July 16, 2019 9:22 AM
  • User-471420332 posted

    I added all above scripts in content page of my master page, please help me to out where i have to add into master, right now all script are in content page. 

    Tuesday, July 16, 2019 9:34 AM
  • User839733648 posted

    Hi mazhar khan,

    Accroding to your description and code, it seems that you have put the first part of the script in the head.

    The elements of the body below have not yet been generated, so document.getElementById("snap") returns null.

    You could put the script at the end of the body.

        <form id="form1" runat="server">
           <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div>
                <video id="video" width="320" height="240"></video>
                <canvas id="canvas" width="320" height="240"></canvas>
                <label id="lbltipAddedComment"></label>
            </div>
            <!-- Modal body -->
            <div class="modal-body text-center">
                Are you sure you want to submit this form?
            </div>
            <!-- Modal footer -->
            <div class="text-center d-block m-auto pb-4">
            <button id="snap" runat="server" class="starttest-btn">Snap</button>
            </div>
            <script type="text/javascript">
                    ...
                document.getElementById("snap").addEventListener("click", function (){
                     context.drawImage(video, 0, 0, 320, 240);
                });
            </script>
        </form>

    Or you could put the execution in the $(function() {} ).

            <script type="text/javascript">
                $(function () {
                    document.getElementById("snap").addEventListener("click", function (){
                        context.drawImage(video, 0, 0, 320, 240);
                      });
                  })
            </script>


    Best Regards,

    Jenifer

    Tuesday, July 16, 2019 9:45 AM
  • User-471420332 posted


    image file storing black image, why i thought its addeventlistener issue image storing black image, can you help me.

    Tuesday, July 16, 2019 10:23 AM
  • User839733648 posted

    Hi mazhar khan,

    image file storing black image, why i thought its addeventlistener issue image storing black image, can you help me.

    Have you tried to modify the position of your first part of script?

    Uncaught TypeError: Cannot read property 'addEventListener'

    Does this error still exist?

    I think that you should try to fix the issue first.

    And then if there exists other issue, we should check that error and find how to fix step by step.

    Best Regards,

    Jenifer

    Wednesday, July 17, 2019 6:52 AM