chrome浏览器支持PictureInPicture即画中画接口

2,683 阅读2分钟
原文链接: www.shuaihua.cc

画中画接口允许网站创建一块可浮动、可缩放、可拖拽的视频播放区域,该区域永远至于窗口顶层,用户可以在操作其他任务时继续观看视频,大大提升桌面空间利用率与用户时间效率。

The Picture-in-Picture API allows websites to create a floating video window that is always on top of other windows so that users may continue consuming media while they interact with other sites or applications on their device.

小试牛刀

我从youtube上随便找了一段视频,通过在线转码工具将这段小视频下载到本地。页面由三个标签及一段javascript脚本组成:

  • <video> 视频标签的播放源指向本地的一段视频。
  • <button> 控制视频的播放与暂停。
  • <button> 触发画中画功能。

最终效果如下方GIF所示:

测试环境

  • windows 10 (64 位)
  • chrome 版本 72.0.3608.4(正式版本)

示例代码

以下示例代码是我为了验证画中画关键特性快速书写而成的,并不能保证其完全符合任何代码规范或标准。

html

<video src="video.mp4" autoplay control loop id="videoEl"></video>
<button type="button" id="play" name="button">play</button>
<button type="button" id="pip" name="button">pip</button>

css

#videoEl {
  width: 900px;
}

js

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)
      }
    });
})

关键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赋值函数,可以用来处理当用户缩放画中画窗口时的操作。


扩展阅读: