Barcode and camera
html
JavaScript
<div>
<div class="camBox">
<video id="video" autoplay>Video stream not available.</video>
<button id="takePicture" disabled>
<i class="material-icons">photo_camera</i>
</button>
</div>
<div class="camBox">
<img id="photoPreview" alt="Camera capture" />
</div>
</div>
<script>
(async () => {
let video = document.querySelector("#video");
let photoPreview = document.querySelector("#photoPreview");
let takePicture = document.querySelector("#takePicture");
let canvas = document.createElement("canvas");
video.addEventListener("mouseover", async function() {
try {
let cameraStream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: "environment",
},
audio: false,
});
// on stream start video
video.srcObject = cameraStream;
video.play();
// Enable button
takePicture.disabled = false;
takePicture.addEventListener(
"click",
function (ev) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
// Take video picture
canvas
.getContext("2d")
.drawImage(video, 0, 0, canvas.width, canvas.height);
// Show picture to preview
photoPreview.setAttribute("src", canvas.toDataURL("image/png"));
ev.preventDefault();
},
false
);
} catch (err) {
console.error("Error: " + err);
}
});
})();
</script>
<style>
:root {
--video-height: 256px;
}
.camBox {
position: relative;
border-radius: 8px;
background-color: black;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08);
width: calc(var(--video-height) * 16 / 9);
height: var(--video-height);
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
color: white;
margin: 8px;
}
.camBox video {
height: 100%;
object-fit: fill;
}
.camBox img {
height: 100%;
object-fit: fill;
}
#takePicture {
position: absolute;
bottom: 24px;
right: 24px;
height: 48px;
width: 48px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08);
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
border: none;
outline: none;
background-color: white;
}
#takePicture:hover {
box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
0 17px 50px 0 rgba(0, 0, 0, 0.19);
}
#takePicture:active {
transform: translateY(2px);
}
</style>