0

I am trying to program a camera website. The stream seems to work, and I can see the canvas captures its image when it was drawn, but it seems I have a problem when it comes to changing it into an image and then downloading it. SOS

function capture() {
var canvas = document.getElementById('canvas');     
var video = document.getElementById('video');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 140, 0, video.videoWidth, video.videoHeight);
var data = canvas.toDataURL();
var prev = window.location.href;
window.location.href = data.replace("image/png", "image/octet-stream");
window.location.href = prev;
  • May you make sure that the code you provide is enough for us to debug the issue? See how to make a [mcve]. – evolutionxbox Aug 16 '20 at 18:11
  • This [link](https://stackoverflow.com/a/28890083/14023365) might be useful. In your case, you need to set `a.href = canvas.toDataURL();` This change is with comparison to the code present in the mentioned link – Hemant Halwai Aug 16 '20 at 18:33

1 Answers1

0

Replace your code with the following, noting that 'capture.png' need to be replaced with actual file name you want to save file as. 'image/png' with mime type, and that toBlob function has a third quality parameter for when mimeType is image/jpeg or image/webp.

var canvas = document.getElementById('canvas');     
var video = document.getElementById('video');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 140, 0, video.videoWidth, video.videoHeight);
var blob = canvas.toBlob(function (blob) {
var anchor = document.createElement('a');
anchor.style.display = 'none';
document.body.appendChild(anchor);
var url = window.URL.createObjectURL(blob);
anchor.href = url;
anchor.download = 'capture.png';
anchor.click();
window.setTimeout(() => {
    window.URL.revokeObjectURL(url);
    document.body.removeChild(anchor);
  }, 100);
}, 'image/png');
Sherif Elmetainy
  • 4,034
  • 1
  • 13
  • 22