我们就得截取每个视频的封面图来,因为video标签有个属性poster是用来储存封面图地址的,但需注意先用本地视频,非本地视频会有跨域截取问题,这个得跟后端开发协作处理。这是一款截取视频源的封面图poster,监听视频播放状态的功能;
使用方法:
1、head引入css部分
<style>
.video-con{ width: 300px; height: 150px; position: relative; margin-bottom: 20px;}
.video-con .video{ width: 100%; height: 100%;}
.video-con .btn{ width: 64px; height: 64px; background: transparent url("img/play-btn.png") no-repeat;
position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); border: none;
}
.video-con .btn.pause{ background-image: url("img/pause-btn.png");}
</style>
2、body引入HTML代码
<div class="video-con">
<video class="video" poster="">
<source src="mp4/1.mp4" >
</video>
<button type="button" class="btn js-play-btn"></button>
</div>
<!--html5的video-->
<script type="text/javascript">
// 视频------视频截图 ~~ 视频播放状态 ~~
const setMedia = function(video, scale = 0.8) {
// 设置poster属性:(非本地视频资源会有跨域截图问题)
video.addEventListener('loadeddata', function(e) {
// 拿到图片
let canvas = document.createElement('canvas');
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
let src = canvas.toDataURL('image/png');
// 显示在dom,测试用
(function(flag = true) {
if (!flag) {return;}
let img = document.createElement('img');
img.src = src;
document.body.appendChild(img);
})(0);
// 设置属性
video.setAttribute('poster', src);
});
// -------------------------------------------------------------------------------------
//检测视频播放状态:
//播放按钮
let playBtn = video.parentNode.childNodes[2].nextSibling;
//设置状态
function vidplaySate(e) {
if (video.paused) {
video.play();
playBtn.classList.add('pause');
} else {
video.pause();
playBtn.classList.remove('pause');
}
}
//点击监听
video.addEventListener('click', vidplaySate, false);
playBtn.addEventListener('click', vidplaySate, false);
//结束监听
video.addEventListener('ended',function () {
playBtn.classList.remove('pause');
});
};
//视频:
let videos = document.querySelectorAll('video');
videos.forEach((video) => {
setMedia(video);
});
</script>