Picture in picture web api with Javascript
When you watch Youtube, there is a miniplayer in the right corner which is same as picture in picture function. I think this is very useful for mordern people's life,who can do multiple thing at the same time,such as browsering website while watching some videos or doing notes when having class on one screen.
The video screen can be dragged anywhere you want and resize to any size you want. Efficient tool.
When searching picture in picture,there is a chrome extension choice.Here is the customize version for developer.
CODE SEPERATE BELOW:
HTML
video tag is the container for video display with the button to trigger.
CSS
font from Google font as you choice.
First,make sure all the stuff in the center of the body,just for displaying.
Giving button some animations,like box-shadow and background.
JAVASCRIPT
Get the DOM with ID.
First, the broswer needs to fetch the screen with Screen Capture API.
captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
After capture the share screen,you can choose which one to display.
Set the fetched screen video to the display position in the Html with srcObject.
The
srcObject
property of the HTMLMediaElement
interface sets or returns the object which serves as the source of the media associated with the HTMLMediaElement
. The object can be a MediaStream
, a MediaSource
, a Blob
, or a File
When meta data for a video is loaded, it's time to excute the function to play the video. onloadedmetadata Event
When click the button,it should be disabled.And request picture to picture API.
requestPictureInPicture().This method returns a promise that places the video in a mini window on the bottom-right side of the screen by default when resolved, although it can be moved around by the user.
The article about picture-in-picture web API
The events are
enterpictureinpicture
and leavepictureinpicture
which, as their names imply, fire when a video enters or exits picture-in-picture mode, respectively.video.addEventListener('enterpictureinpicture', () => {
button.textContent = 'Exit Picture-in-Picture mode';
});
video.addEventListener('leavepictureinpicture', () => {
button.textContent = 'Enter Picture-in-Picture mode';
});
Code Github