使用 canvas 绘制视频
安卓/ios 对 video 兼容较差,使用 canvas 可以很好的解决播放/全屏/自定义控件问题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=640,user-scalable=0,target-densitydpi=device-dpi" />
<style>
* {
margin: 0;
padding: 0;
}
.controls {
margin: 10px;
}
.controls button {
padding: 5px 10px;
margin-right: 10px;
border: none;
}
video {
width: 375px;
height: 160px;
}
</style>
</head>
<body>
<div class="controls">
<button id="play">播放</button>
<button id="paused">暂停</button>
<button id="hide-video">显示/不显示video</button>
</div>
<canvas
id="canvas"
width="375"
height="160"
style="background: #000"
></canvas>
<video
id="video"
style="display: auto"
width="100%"
preload="auto"
controls
muted="true"
playsInline="true"
webkit-playsinline="true"
x-webkit-airplay="true"
x5-video-player-type="h5"
x5-video-player-fullscreen="false"
x5-video-orientation="portraint"
>
<source src="https://assets.monogogo.cn/video/1598320823944_cps.mp4" type="video/mp4"></source>
</video>
</body>
<script>
var canvas = document.getElementById('canvas')
var video = document.getElementById('video')
var play = document.getElementById('play')
var paused = document.getElementById('paused')
var hide = document.getElementById('hide-video')
var ctx = canvas.getContext('2d')
var animation = null;
play.addEventListener('click', function() {
video.play()
draw(video, canvas, ctx)
})
paused.addEventListener('click', function() {
video.pause()
})
hide.addEventListener('click', function() {
if(video.style.display === 'none') {
video.style.display = ''
} else {
video.style.display = 'none'
}
})
function draw(video, canvas, ctx) {
if(video.paused || video.ended) {
cancelAnimationFrame(animation)
}
ctx.drawImage(video, 0, 0, 375, 160)
animation = requestAnimationFrame(function() {
draw(video, canvas, ctx)
})
}
</script>
</html>