通过监听<video>元素的播放(onplay)和暂停(onpause)事件, 并结合window的请求动画帧方法(requestAnimationFrame), 完成在Canvas画布上绘制视频需求
<!-- @format -->
<!DOCTYPE html>
<html>
<body>
<video id="video" width="600" height="400" muted controls src="./1.mp4"></video>
<canvas id="canvas" style="width: 1000px; height: 500px" width="1920" height="1080"></canvas>
</body>
</html>
<script type="text/javascript">
const video = document.getElementById('video')
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
let isPlay = false
function render() {
if (isPlay) {
ctx.drawImage(video, 0, 0, 1920, 1080)
}
requestAnimationFrame(render)
}
// 播放
video.onplay = () => {
isPlay = true
render()
}
video.onpause = () => (isPlay = false)
video.onended = () => (isPlay = false)
</script>