Save image captured by webcam from an html page with javascript

Asked

Viewed 384 times

1

Hello, I made a capture with my webcam of an image using javascript and made an appendchild of the url in a div tag in html. How do I save this image to my computer?

webcam.js

  var player = document.getElementById('player');
  var snapshotCanvas = document.getElementById('snapshot');
  var captureButton = document.getElementById('capture');

  var handleSuccess = function(stream) {
    // Attach the video stream to the video element and autoplay.
    player.srcObject = stream;
  };

  captureButton.addEventListener('click', function() {
    var context = snapshot.getContext('2d');
    // Draw the video frame to the canvas.
    context.drawImage(player, 0, 0, snapshotCanvas.width,
        snapshotCanvas.height);

    var imgBse64 = snapshotCanvas.toDataURL("image/jpeg");

    var image = document.createElement("img")
    image.setAttribute("src", imgBse64)


    var wrapper = document.querySelector('.fotos')
    wrapper.appendChild(image)

    //var arr = document.querySelectorAll('.fotos img')
  });

  navigator.mediaDevices.getUserMedia({video: true})
      .then(handleSuccess);

home html.

<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="snapshot" width=320 height=240></canvas>
<script type="text/javascript" src="{% static 'js/webcam.js' %}"></script>
*<div class="fotos">*
</div>

1 answer

0


Once you have the string in Base64 you can download it dynamically like this:

saveBase64AsFile(base64, fileName) {    
    var link = document.createElement("a");

    link.setAttribute("href", base64);
    link.setAttribute("download", fileName);
    link.click();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.