JSFiddle - React, Tailwind, and code Playground
by Casufi
HTML
<div class="item">
<video id="video" autoplay="autoplay" style="display:none"></video>
</div>
<div class="item">
<canvas id="canvas" width="320" height="240"></canvas>
</div>
JavaScript
var c = document.getElementById('canvas');
var v = document.getElementById('video');
var con = c.getContext('2d');
var videoStreamUrl = false;
var isStreaming = false;
w = 600;
h = 420;
var maxbright = 200;
var minbright = 90;
var limit = 30;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL.createObjectURL = window.URL.createObjectURL || window.URL.webkitCreateObjectURL || window.URL.mozCreateObjectURL || window.URL.msCreateObjectURL;
var goingGrey = function () {
var badPixels = 0;
var imageData = con.getImageData(0, 0, w, h);
var data = imageData.data;
for (var i = 0; i < data.length; i += 4) {
var bright = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
//var bright = 85;
data[i] = bright;
data[i + 1] = bright;
data[i + 2] = bright;
if (bright > maxbright || bright < minbright) badPixels++;
}
var percentage = 100 * badPixels / (data.length / 4);
con.putImageData(imageData, 0, 0);
if (percentage > limit) {
con.fillStyle = "red";
} else {
con.fillStyle = "green";
}
con.font = "bold 16px Arial";
con.fillText(percentage, 20, 20);
};
navigator.getUserMedia({
video: true
}, function (stream) {
// получаем url поточного видео
videoStreamUrl = window.URL.createObjectURL(stream);
// устанавливаем как источник для video
v.src = videoStreamUrl;
v.addEventListener('canplay', function (e) {
if (!isStreaming) {
// videoWidth isn't always set correctly in all browsers
if (v.videoWidth > 0) h = v.videoHeight / (v.videoWidth / w);
c.setAttribute('width', w);
c.setAttribute('height', h);
...