I'm trying to take a picture with a webcam ... I'm relatively new to Javascript and I'm taking a chorus!
Follow my code:
//função para iniciar a camera
function startCamera(){
navigator.mediaDevices.getUserMedia({
video:{facingMode:'environment'},
audio:true
})
.then((stream) => {
document.getElementById('video').srcObject=stream
})
}
//função para parar a camera
function stopCamera(){
document.getElementById('video')
.srcObject
.getVideoTracks()
.forEach(track => track.stop())
}
//ligar a camer automaticamente
window.addEventListener("DOMContentLoaded", startCamera())
//função para tirar foto
document.querySelector('#btnStart').addEventListener('click', event => {
const canvas = document.getElementById('pic')
const context = canvas.getContext('2d')
const video = document.getElementById('video')
//tamanho da foto mesmo tamanho do video
canvas.width = video.offsetWidth
canvas.height = video.offsetHeight
//desenha o video no canvas
context.drawImage(video, 0, 0, canvas.witdh, canvas.height)
//metodo do canvas para pegar um objeto Blob
canvas.toBlob(function(blob){
const url = URL.createObjectURL(blob)
stopCamera()
}, 'image/jpeg', 0.95)
//closeCamera()
})
<video src="" id="video" muted autoplay></video>
<canvas id="pic"></canvas>
<input type="button" id="btnStart" value="Tirar Foto">
So far I've only been able to turn the camera on and show 'LIVE' ... I could not make the photo appear on the canvas ... the image is black when I click the button to take the picture.