I had watched the following tutorial https://youtu.be/BTWPDboW38o?si=_21TOjCfrXC3VWIL and tried the same. What I expect is, I want to change the background color of document based on the color of video stream. But it is always returning rgb(0,0,0).
'use strict';
try {
const w = window,
d = document,
ng = navigator,
id = e => {
return d.getElementById(e)
},
cn = id('lh'),
i = id('i'),
o = id('o'),
cx = cn.getContext('2d', {
willReadFrequently: true
}),
face = r => ng.mediaDevices.getUserMedia({
video: {
facingMode: {
exact: 'user'
}
}
}).then(s => {
i.srcObject = s;
i.onloadedmetadata = e => {
setInterval(() => {
let c = 0,
k = -4,
h = cn.height = i.videoHeight,
w = cn.width = i.videoWidth,
dt = cx.getImageData(0, 0, w, h),
io = dt.data,
dl = io.length,
R, G, B;
R = G = B = 0;
cx.drawImage(i, 0, 0, w, h);
o.src = cn.toDataURL('image/webp');
while ((k += r * 4) < dl) {
++c;
R += io[k];
G += io[k + 1];
B += io[k + 2]
};
['R', 'G', 'B'].forEach(e1 => {
eval(e1 + '=' + `~~(${e1}/c)`)
});
let rgb = `rgb(${R},${G},${B})`;
d.body.style.background = rgb
}, -1)
}
});
face(4)
} catch (e) {
alert(e)
}
I expect it should change the background color of document based on video stream.
ok, heres whats wrong with your code
after assigning the
srcObjectof avideoelement you have to call playin the
setIntervalfunction when you assign the values ofhandwyou also set thewidthandheightof thecanvas, doing this clears the canvasnotes:
you could do with some clarification that after invoking
face(4)thethenfunction is actually part of thegetUserMedia, it confused me for a whileits probably the most elaborate way perform a
Math.floorI have ever seeni added a stop feature so it can be turned off without reloading the page
im afraid that it wont actually run in the stackoverflow website, i think they must have webcam access turned off and wont allow video to play
ive created a much neater version for anyone who visits this page at a later date, it needs a canvas element and its derived 2d context
i thought this was a nice little project so ive added a working example, i dont think a lot of these sites that allow code generation allow video, anyway heres what all the fuss is about