视频画中画requestPictureInPicture介绍及案例

5642次浏览

前言

视频画中画是我们在浏览视频网站经常遇到的技术,可以增加用户体验,用户在下滑视频的时候,相关视频可以浮在窗口表面,这个技术pc浏览器大部分已经支持,但是移动端目前很多不支持,本文仅简单介绍一下这个技术。

效果

感兴趣的朋友可以看下效果 http://resource.haorooms.com/showdemo.html?id=286

这个实现很简单。代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>haorooms博客-前端博客-案例-画中画demo</title>
  <style>
    #videoEl {
  width: 600px;
}
  </style>
</head>
<body>
  <video src="video.mp4" autoplay control loop id="videoEl"></video>
  <br/>
<button type="button" id="play" name="button">播放</button>
<button type="button" id="pip" name="button">画中画</button>

<script>

var videoEl = document.querySelector("#videoEl")
console.log(videoEl.__proto__ )
videoEl.onenterpictureinpicture = function(e){
  console.log('enter pip')
}
videoEl.onleavepictureinpicture = function(e){
  console.log('leave pip')
}
videoEl.onplay = function(e){
  console.log('video play')
}
videoEl.onpause = function(e){
  console.log('video pause')
}
document.querySelector("#play").addEventListener('click', function(e){
  videoEl.play()
})
document.querySelector("#pip").addEventListener('click', function(e){
  videoEl.requestPictureInPicture()
    .then(function(pipWindow){
      pipWindow.onresize = function(e){
        console.log(e.target.width)
      }
    });
})
</script>
</body>
</html>

关键API

所有HTMLVideoElement类的实例对象都继承了父类原型链上关于画中画的方法,以下方法是父类原型链上拥有的方法。

HTMLVideoElement.prototype.disablePictureInPicture
HTMLVideoElement.prototype.requestPictureInPicture

检测支持

通过检测

document.pictureInPictureEnabled

是否为真判断当前浏览器是否支持画中画,document对象中还有一个属性document.pictureInPictureElement,该属性指向当前激活了画中画特性的元素。

事件

通过为实例化DOM元素对象的三个事件监听器赋值事件监听函数:

    videoElement.onenterpictureinpicture = function(e){
  // e.target 指向当前DOM元素
}
videoElement.onleavepictureinpicture = function(e){
  // e.target 指向当前DOM元素
}

其中,onenterpictureinpicture事件监听函数触发后,传入事件监听函数内的事件对象内包含pictureInPictureWindow属性,该属性指向悬浮的画中画窗口对象,该画中画窗口对象包含一些有关画中画窗口的属性和一个监听画中画窗口缩放的事件监听函数

 pictureInPictureWindow {
  width,
  height,
  onresize
}

为onresize赋值函数,可以用来处理当用户缩放画中画窗口时的操作。

兼容性

画中画api的兼容性可以查看 https://caniuse.com/?search=requestPictureInPicture

目前看到大部分pc浏览器都支持这个属性,但是移动端目前不支持。所以使用的时候要谨慎

小结

haorooms博客-前端博客的排名又上来了,之前主要是因为第三方恶意采用haorooms关键词,导致haorooms关键词排名剧烈下滑!欢迎大家关注支持。

相关文章: