canvas播放视频
思路
通过监听video的play事件,不断的获取最新的video视频帧数据,然后将最新的视频帧通过drawImage绘制到canvas中。同样的思路,可以通过navigator.getUserMedia获取摄像头数据,然后通过canvas绘制出来,或者通过websocket/webrtc等方法传输给服务器或者其它客户端就可以实现视频聊天。
代码
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>video play in canvas</title> <style> #video { width: 600px; height: 400px; } </style> </head> <body> <div> <video id="video" src="movie.mp4" controls></video> <br/> <button id="play-button">play</button> <button id="pause-button">pause</button>
<br/> <canvas id="canvas" width="600" height="400"></canvas> </div> <script> var video = document.getElementById('video'); var playButton = document.getElementById('play-button'); var pauseButton = document.getElementById('pause-button'); var canvas = document.getElementById("canvas"); var context = canvas.getContext('2d'); playButton.onclick = function () { video.play(); }; pauseButton.onclick = function () { video.pause(); }; video.addEventListener('play', playCallBack); function playCallBack() { if(video.paused || video.ended) { return; } captureFrame(); setTimeout(playCallBack, 0); } function captureFrame() { context.drawImage(video, 0, 0, 600, 400); } </script> </body> </html>
效果如下: