English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Sample Code for JavaScript to Open Camera and Take Screenshot Upload

Let's get straight to the point, a complete step of opening the camera with JS and uploading the screenshot to the backend.

1. The main method used to open the camera is getUserMedia, and then the obtained media stream is placed in the video tag.

2. The main method used to capture images is canvas drawing, using the drawImage method to draw the content of video to canvas.

3. Upload the captured content to the server and convert the content of canvas to base.64The format is uploaded, and the backend (PHP) uses file_put_contents to convert it to an image.

It should be noted that there may be some problems with the camera in browsers other than chrome, which may also be an old problem. Therefore, the following code is mainly based on chrome usage.

For example, the error reported in the latest version of FireFox, for some reason.

1. Open the camera

getUserMedia has two versions, new and old. It is recommended to use the new version.

The old version is located under the navigator object, which varies depending on the browser.

 // Get media method (old method)
  navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMeddia || navigator.msGetUserMedia; 
if (navigator.getMedia) {
    navigator.getMedia({
      video: true
    }, function(stream) {
      mediaStreamTrack = stream.getTracks()[0];
      video.src = (window.URL || window.webkitURL).createObjectURL(stream);
      video.play();
    }, function(err) {
      console.log(err);
    });
  } 

The first parameter indicates whether to use video (video) or audio (audio).

The second parameter indicates the callback after the call succeeds, which includes one parameter (MediaStream). In the old version, you could directly call MediaStream.stop() to close the camera, but this has been deprecated in the new version. You need to use MediaStream.getTracks()[index].stop() to close the corresponding Track.

The third parameter indicates the callback after the call fails.

The new version is located under the navigator.mediaDevices object.

if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    }).then(function(stream) {
      console.log(stream);
      mediaStreamTrack = typeof stream.stop === 'function'63; stream : stream.getTracks()[1];
      video.src = (window.URL || window.webkitURL).createObjectURL(stream);
      video.play();
    }).catch(function(err) {
      console.log(err);
    })
  } 

Similar to the old version, but this method returns a Promise object that can be used with then and catch to represent success and failure callbacks.

It should be noted that the Tracks array returned by MediaStream.getTracks() is sorted in reverse order according to the first parameter.

}

For example, now the definition is
  video: true,
  audio: true
} 

{1To close the camera, you need to call MediaStream.getTracks()[

].stop();

Similarly, 0 corresponds to the audio track

Use createObjectURL to write the MediaStream into the video tag, which can store real-time media stream data (and also allows for real-time viewing of the image)

  The webkitURL object is not supported in old versions, and the URL object needs to be used200" height="150"></<video width="
  <canvas width="200" height="150"></canvas>
  <p>
    <button id="snap">Capture Image</button>
    <button id="close">Close Camera</button>
    <button id="upload">Upload Image</button>
  </p>
  <img id="uploaded" width="200" height="150" /> 

2. Capture the image

The content can be written in

 // Capture image
  snap.addEventListener('click', function() {
    context.drawImage(video, 0, 0, 200, 150);
  }, false); 

3. Close the camera

 // Close the camera
  close.addEventListener('click', function() {
    mediaStreamTrack && mediaStreamTrack.stop();
  }, false); 

4. Upload the captured image

canvas.toDataURL('image/png')

// Upload the captured image
  upload.addEventListener('click', function() {
    jQuery.post('/uploadSnap.php', {
      snapData: canvas.toDataURL('image/png')
    }).done(function(rs) {
      rs = JSON.parse(rs);
      console.log(rs);
      uploaded.src = rs.path;
    }).fail(function(err) {
      console.log(err);
    });
  }, false); 

While the backend (PHP) here converts the obtained content into an image file for saving

It should be noted that the base64The header information field should be removed before saving, otherwise the image may be corrupted and cannot be opened.

 <?php
  
  $snapData = str_replace('data:image/png;base64
  // $snapData = str_replace(' ', '+', $snapData);
  $img = base64_decode($snapData);
  $uploadDir = 'upload/';
  $fileName = date('YmdHis', time()) . uniqid();
  if (!(file_put_contents($uploadDir . $fileName, $img))) {
    echo json_encode(array('code' => 500, 'msg' => 'File upload failed'));
  } else {
    echo json_encode(array('code' => 200, 'msg' => 'File upload successful', 'path' => $uploadDir . $fileName));
  }
?> 

Complete JS code

<script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
  function $(elem) {
    return document.querySelector(elem);
  }
  // Get media method (old method)
  navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMeddia || navigator.msGetUserMedia;
  var canvas = $('canvas'),
    context = canvas.getContext('2d'),
    video = $('video'),
    snap = $('#snap'),
    close = $('#close'),
    upload = $('#upload'),
    uploaded = $('#uploaded'),
    mediaStreamTrack;
  // Get media method (new method)
  // Use the new method to open the camera
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    }).then(function(stream) {
      console.log(stream);
      mediaStreamTrack = typeof stream.stop === 'function'63; stream : stream.getTracks()[1];
      video.src = (window.URL || window.webkitURL).createObjectURL(stream);
      video.play();
    }).catch(function(err) {
      console.log(err);
    })
  }
  // Use the old method to open the camera
  else if (navigator.getMedia) {
    navigator.getMedia({
      video: true
    }, function(stream) {
      mediaStreamTrack = stream.getTracks()[0];
      video.src = (window.URL || window.webkitURL).createObjectURL(stream);
      video.play();
    }, function(err) {
      console.log(err);
    });
  }
  // Capture image
  snap.addEventListener('click', function() {
    context.drawImage(video, 0, 0, 200, 150);
  }, false);
  // Close the camera
  close.addEventListener('click', function() {
    mediaStreamTrack && mediaStreamTrack.stop();
  }, false);
  // Upload the captured image
  upload.addEventListener('click', function() {
    jQuery.post('/uploadSnap.php', {
      snapData: canvas.toDataURL('image/png')
    }).done(function(rs) {
      rs = JSON.parse(rs);
      console.log(rs);
      uploaded.src = rs.path;
    }).fail(function(err) {
      console.log(err);
    });
  }, false);
  </script>

That's all for this article. I hope it will be helpful to your learning and that everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w.codebox.com.3Please send an email to notice#w.codebox.com (replace # with @ when sending email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.

You May Also Like