实现的效果图
全屏的效果图
由于video自带的全屏功能,层级最高,导致自定义的抓拍的按钮无法在全屏时显示,故而自己写了全屏的按钮来实现全屏的功能。
如果有小伙伴有实现自带全屏可以显示自定义按钮的话,欢迎在评论区告诉我,谢谢!
基于vue2.0的项目中实现的
屏蔽video自身的全屏图标
.videoArea video::-webkit-media-controls-fullscreen-button {
display: none;
}
vue代码
<template>
<div>
<video
id="videoElement"
ref="videoItem"
src="../images/myvideo.mp4"
:style="isFull?{height: '100%'}:{height: 'calc(100vh - 298px)'}"
controls
muted
autoplay
width="100%"
></video>
<div class="opBtn">
<div class="snapArea" @click="snapClick('videoElement')"><img src="../images/camera.png" width="25px" height="25px">抓拍</div>
<!-- 全屏按钮 注意这两个地方自己去下载两个全屏和退出全屏的图标-->
<div class="full" @click="fullScreen('videoElement')"><img src="../images/exit.png" v-if="isFull" width="25px" height="25px">
<img src="../images/full.png" v-else width="25px" height="25px">{{isFull?'退出全屏':'全屏'}}</div>
</div>
</div>
</template>
抓拍并下载主要使用canvas,并创建一个a标签,利用a标签的download属性来下载图片
//抓拍
snapClick(id){//id是video的id
let video = document.getElementById(id);
let canvas = document.createElement("canvas");
let tempLink = document.createElement('a');
let ctx = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
tempLink.href=canvas.toDataURL();
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank');
}else{
tempLink.setAttribute('download', '下载.png');//自定义下载的名字,需要加上.png的后缀
}
document.body.appendChild(tempLink);
tempLink.click();
setTimeout(function () {//移除a标签
document.body.removeChild(tempLink);
}, 100)
},
全屏的实现用isFull变量来标识,并且根据isFull动态设置video的样式来控制是否是全屏。
//全屏,因为video全屏层级原因,抓拍无法在全屏时显示,故而单独写了一个全屏的按钮。
fullScreen(){
this.isFull=!this.isFull//每次取反
if(this.isFull){//全屏
var el = document.getElementById('videoArea1');
var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;
if (rfs) {
rfs.call(el);
}
}else{//退出全屏
document.exitFullscreen ? document.exitFullscreen() :
document.mozCancelFullScreen ? document.mozCancelFullScreen() :
document.webkitExitFullscreen ? document.webkitExitFullscreen() : '';
}
},
图标的样式
.videoArea {
display: flex;
align-items: center;
position: relative;
}
.opBtn {
position: absolute;
right: 10px;
}
.snapArea {
cursor: pointer;
color: #fff;
background-color: rgba(63, 69, 82, 0.5);
width: 110px;
height: 50px;
line-height: 50px;
align-items: center;
display: flex;
justify-content: space-around;
border-radius: 10px;
z-index: 9999999999 !important;
}
.full {
cursor: pointer;
margin-top: 10px;
color: #fff;
background-color: rgba(63, 69, 82, 0.5);
width: 110px;
height: 50px;
line-height: 50px;
align-items: center;
display: flex;
justify-content: space-around;
border-radius: 10px;
z-index: 9999999999 !important;
}