出现报错的原因是xgplayer截图时要用到window对象,而在乾坤子应用中找不到window,因此会报错
解决思路
使用xgplayer提供的自定义插件,和原始截图功能代码(规避掉window)结合,开发一个截图功能。
功能开发前置能力
自定义截图插件代码参考
import { Plugin } from 'xgplayer'
const { POSITIONS } = Plugin
export default class demoPlugin extends Plugin {
// 插件的名称,将作为插件实例的唯一key值
static get pluginName() {
return 'shootImg'
}
static get defaultConfig () {
return {
// 挂载在controls的右侧,如果不指定则默认挂载在播放器根节点上
position: POSITIONS.CONTROLS_RIGHT,
index: 7
}
}
constructor (args) {
super(args)
}
beforePlayerInit () {
// TODO 播放器调用start初始化播放源之前的逻辑
}
afterPlayerInit () {
// TODO 播放器调用start初始化播放源之后的逻辑
}
afterCreate () {
const { player } = this
const screenShotOptions = { ...player.config.screenShot, fileName: '视频截图' }
let callBack = null
player.video.setAttribute('crossOrigin', 'anonymous')
let encoderOptions = 0.92
if (screenShotOptions.quality || screenShotOptions.quality === 0) {
encoderOptions = screenShotOptions.quality
}
const type = screenShotOptions.type === undefined ? 'image/png' : screenShotOptions.type
const format = screenShotOptions.format === undefined ? '.png' : screenShotOptions.format
const canvas = document.createElement('canvas')
const canvasCtx = canvas.getContext('2d')
const img = new Image()
canvas.width = this.config.width || 600
canvas.height = this.config.height || 337.5
const saveScreenShot = function (data, filename) {
const saveLink = document.createElement('a')
saveLink.href = data
saveLink.download = filename
const event = document.createEvent('MouseEvents')
/************Document.defaultView替换window******************/
event.initMouseEvent('click', true, false, Document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
saveLink.dispatchEvent(event)
}
player.screenShot = function (save = true) {
save = screenShotOptions.saveImg === undefined ? save : screenShotOptions.saveImg
canvas.width = player.video.videoWidth || 600
canvas.height = player.video.videoHeight || 337.5
callBack = screenShotOptions.callBack
img.onload = (function () {
canvasCtx.drawImage(player.video, 0, 0, canvas.width, canvas.height)
img.src = canvas.toDataURL(type, encoderOptions).replace(type, 'image/octet-stream')
const screenShotImg = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream')
const saveFileName = screenShotOptions.fileName || player.lang.SCREENSHOT
player.emit('screenShot', screenShotImg)
if (save && callBack) {
callBack(screenShotImg, saveFileName, format)
} else {
save && saveScreenShot(screenShotImg, saveFileName + format)
}
})()
}
this.onClick = () => {
console.log('当前插件根节点点击事件')
console.log('this.player', this.player)
player.screenShot()
}
// 对当前插件根节点绑定click事件
this.bind('click', this.onClick)
// TODO 插件实例化之后的一些逻辑
}
destroy () {
this.unbind('click', this.onClick)
// 播放器销毁的时候一些逻辑
}
render () {
return `<div class="xg-options-icon show player-shoot-img-plugin">
<div class="xgplayer-icon btn-text">
<span class="icon-text">截图</span>
</div>
</div>`
}
}