getUserMedia PIP
by juberti
HTML
<button id=b>Start</button>
<button id=b2>PIP</button>
<br>
<video width="128" height="96" id=v autoplay>
</video>
<canvas width="128" height="192" id=c></canvas>
<video width="128" height="192" id=v2 autoplay>
CSS
#c {
display: none;
}
#v {
border: 1px black;
}
#v2 {
display: none;
}
JavaScript
var b = document.getElementById('b');
var b2 = document.getElementById('b2');
var v = document.getElementById('v');
var v2 = document.getElementById('v2');
var c = document.getElementById('c');
var context = c.getContext('2d', {alpha: false});
var pipWindow = null;
var w, h, cw, ch;
window.onfocus = function() {
console.log("onfocus");
if (pipWindow) {
window.setTimeout(function() {
document.exitPictureInPicture();
}, 0);
}
}
window.onblur = function() {
console.log("onblur");
v2.requestPictureInPicture();
}
document.addEventListener("visibilitychange", function() {
console.log(document.visibilityState);
/*if (document.visibilityState == "hidden") {
v2.requestPictureInPicture();
}*/
});
b.onclick = function() {
navigator.mediaDevices.getUserMedia({video:true})
.then(function(stream) {
console.log("streamin'");
v.srcObject = stream;
})
.catch(function(err) {
console.error("No stream for you!")
});
}
b2.onclick = function() {
setTimeout(function() {
console.log("timer firing");
v2.requestPictureInPicture();
}, 0);
}
v.addEventListener('play', function() {
cw = v.clientWidth;
ch = v.clientHeight;
c.width = cw;
c.height = ch * 2;
draw(v,context,cw,ch);
var s2 = c.captureStream();
v2.srcObject = s2;
}, false);
v2.addEventListener('enterpictureinpicture', function(e) {
console.log('pipped = true');
pipWindow = e.pictureInPictureWindow;
pipWindow.addEventListener('enterpictureinpicture', function() {
console.log('resize');
}, false);
}, false);
v2.addEventListener('leavepictureinpicture', function() {
console.log('pipped = false');
pipWindow = null;
}, false);
function draw() {
if(v.paused || v.ended) return;
if (pipWindow || v2.readyState == 0) {
// First, draw it into the backing canvas
context.drawImage(v,0,0,cw,ch);
context.drawImage(v,0,ch,cw,ch);
}
// Start over!
window.requestAnimationFrame(draw);
}