Created
November 29, 2020 21:53
-
-
Save edusantana/aa8134298d33f1f230a2c49d61849a70 to your computer and use it in GitHub Desktop.
Exemplo de código que tira foto da webcam
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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