Created
May 19, 2025 07:00
-
-
Save vaebe/48cb0386e9387e04c6a6eceebd47e2b1 to your computer and use it in GitHub Desktop.
vue3 组合式函数实现视频画中画
This file contains hidden or 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
export function usePictureInPicture(domId: string) { | |
const getDom = () => document.getElementById(domId) as HTMLVideoElement | |
const isPipActive = ref(false) | |
async function enterPip() { | |
const videoDom = getDom() | |
if (videoDom) { | |
try { | |
await videoDom.requestPictureInPicture() | |
isPipActive.value = true | |
} | |
catch (err) { | |
console.error('Failed to enter PiP mode:', err) | |
} | |
} | |
} | |
async function exitPip() { | |
if (document.pictureInPictureElement) { | |
try { | |
await document.exitPictureInPicture() | |
isPipActive.value = false | |
} | |
catch (err) { | |
console.error('Failed to exit PiP mode:', err) | |
} | |
} | |
} | |
async function togglePip() { | |
if (isPipActive.value) { | |
await exitPip() | |
} | |
else { | |
await enterPip() | |
} | |
} | |
function handlePipChange() { | |
isPipActive.value = !!document.pictureInPictureElement | |
} | |
onMounted(() => { | |
document.addEventListener('enterpictureinpicture', handlePipChange) | |
document.addEventListener('leavepictureinpicture', handlePipChange) | |
}) | |
onUnmounted(() => { | |
document.removeEventListener('enterpictureinpicture', handlePipChange) | |
document.removeEventListener('leavepictureinpicture', handlePipChange) | |
}) | |
return { isPipActive, enterPip, exitPip, togglePip } | |
} | |
// 使用 | |
const { togglePip } = usePictureInPicture(`${loginResData.value.id}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment