|
|
|
|
|
|
|
|
|
|
|
function sendValue(value) { |
|
Streamlit.setComponentValue(value) |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function onRender(event) { |
|
|
|
if (!window.rendered) { |
|
|
|
const {height, width, debounce, showControls, startLabel, stopLabel} = event.detail.args |
|
|
|
if (showControls) { |
|
Streamlit.setFrameHeight(45) |
|
} |
|
|
|
if (isNaN(height)) { |
|
height = width / (4/3); |
|
} |
|
|
|
let video = document.getElementById('video'); |
|
let canvas = document.getElementById('canvas'); |
|
let button = document.getElementById('button'); |
|
|
|
let stopped = false; |
|
|
|
video.setAttribute('width', width); |
|
video.setAttribute('height', height); |
|
canvas.setAttribute('width', width); |
|
canvas.setAttribute('height', height); |
|
|
|
function takepicture() { |
|
if (stopped) { |
|
return; |
|
} |
|
let context = canvas.getContext('2d'); |
|
canvas.width = width; |
|
canvas.height = height; |
|
context.drawImage(video, 0, 0, width, height); |
|
|
|
var data = canvas.toDataURL('image/png'); |
|
sendValue(data); |
|
} |
|
|
|
|
|
function stopVideo() { |
|
video.pause(); |
|
video.srcObject.getTracks()[0].stop(); |
|
stopped = true; |
|
} |
|
|
|
function startVideo() { |
|
navigator.mediaDevices.getUserMedia({ video: true }) |
|
.then(function(stream) { |
|
video.srcObject = stream; |
|
video.play(); |
|
}) |
|
.catch(function(err) { |
|
console.log("An error occurred: " + err); |
|
}); |
|
} |
|
|
|
function toggleVideo() { |
|
if (stopped) { |
|
startVideo(); |
|
stopped = false; |
|
} else { |
|
stopVideo(); |
|
stopped = true; |
|
} |
|
|
|
button.textContent = stopped ? startLabel : stopLabel; |
|
} |
|
|
|
if (navigator.mediaDevices.getUserMedia) { |
|
navigator.mediaDevices |
|
.getUserMedia({ video: true }) |
|
.then(function (stream) { |
|
video.srcObject = stream; |
|
}) |
|
.catch(function (error) { |
|
console.log("Something went wrong!"); |
|
console.error(error); |
|
}); |
|
} |
|
|
|
button.addEventListener('click', toggleVideo); |
|
button.textContent = stopped ? startLabel : stopLabel; |
|
|
|
takepicture(); |
|
setInterval(takepicture, debounce); |
|
window.rendered = true |
|
} |
|
} |
|
|
|
|
|
Streamlit.events.addEventListener(Streamlit.RENDER_EVENT, onRender) |
|
|
|
Streamlit.setComponentReady() |
|
|
|
Streamlit.setFrameHeight(0) |
|
|