Created
January 18, 2023 11:27
-
-
Save TheNolle/3a7b017e93d3f39339aec24124220859 to your computer and use it in GitHub Desktop.
Static Image as Picture In Picture | Pure JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const video = document.createElement('video') // video element to then ask for pip | |
// we can't use display = 'none' cause else, pip is blank | |
video.style.width = '0' // hides it so it doesn't destroy the flow, and shows ONLY the pip | |
video.style.height = '0' // hides it so it doesn't destroy the flow, and shows ONLY the pip | |
video.playsInline = true // useful, but not an obligation | |
video.autoplay = true // obligation | |
video.muted = true // useful, but not an obligation | |
const canvas = document.createElement('canvas') // creates the canvas in which we'll put the image | |
canvas.style.display = 'none' // hides it so it doesn't destroy the flow, and shows ONLY the pip | |
const ctx = canvas.getContext('2d') // get the 2d context of it | |
const image = new Image(60, 60) // square image but can be any size, it will be resized in the start function | |
image.addEventListener('load', start) // once loaded, generates the fake video | |
image.src = YOUR-IMG-PATH // load your image | |
function start() { | |
canvas.width = this.naturalWidth // sets the width to the natural width of the image | |
canvas.height = this.naturalHeight // same for height | |
ctx.drawImage(this, 0, 0) // clears canvas (and so, the video) | |
ctx.drawImage(this, 0, 0, this.width, this.height) // displays the image | |
} | |
const stream = canvas.captureStream(1) // 1fps so static image | |
video.srcObject = stream // uses the stream of the canvas (static image) and uses it for src object of the video | |
document.getElementByID('YOUR BUTTON TO SHOW PIP').addEventListener('click', _ => video.requestPictureInPicture()) // shows pip on click | |
document.body.appendChild(video) // required else, pip is blank | |
document.body.appendChild(canvas) // required else, pip is blank |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment