Skip to content

Instantly share code, notes, and snippets.

@edusantana
Created November 29, 2020 21:53
Show Gist options
  • Save edusantana/aa8134298d33f1f230a2c49d61849a70 to your computer and use it in GitHub Desktop.
Save edusantana/aa8134298d33f1f230a2c49d61849a70 to your computer and use it in GitHub Desktop.
Exemplo de código que tira foto da webcam
<html>
<head>
</head>
<body>
<div id="screenshot">
<video autoplay></video>
<img src="" download="new-image-name.webp">
<canvas style="display:none;"></canvas>
<p><button class="capture-button">Capture video</button>
</p>
<p><button id="screenshot-button" disabled="">Take screenshot</button></p>
<p>Para enviar a imagem, extrair o conteúdo de img.src (base64): inspecione para entender.</p>
</div>
<script>
// verifica se navegador surpota mediaDevices
function hasGetUserMedia() {
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}
if (hasGetUserMedia()) {
// Good to go!
const constraints = {
video: true,
};
const captureVideoButton = document.querySelector(
"#screenshot .capture-button"
);
const screenshotButton = document.querySelector("#screenshot-button");
const img = document.querySelector("#screenshot img");
const video = document.querySelector("#screenshot video");
const canvas = document.createElement("canvas");
captureVideoButton.onclick = function () {
navigator.mediaDevices
.getUserMedia(constraints)
.then(handleSuccess)
.catch(handleError);
};
screenshotButton.onclick = video.onclick = function () {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0);
// Other browsers will fall back to image/png
img.src = canvas.toDataURL("image/webp");
};
function handleSuccess(stream) {
screenshotButton.disabled = false;
video.srcObject = stream;
}
} else {
alert("getUserMedia() is not supported by your browser");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment