1. 程式人生 > >簡單地利用canvas載入視訊

簡單地利用canvas載入視訊

canvas載入視訊和圖片是一樣的,使用drawImage,區別就是給一個定時器不停的抓取每幀的畫面,放入Canvas畫布裡面,這個辦法有點簡單粗暴,原理為:監聽了video的play事件,並設定定時器,每20ms呼叫一次drawImage,當video的ended事件觸發時,清除定時器。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
    <video src="p03501roz02.p702.1.mp4" id="video1" width="270" controls autoplay></video>
    <canvas id="myCanvas" width="270" height="135"></canvas>
    <script>
        var v = document.getElementById('video1')
        var c = document.getElementById('myCanvas')
        var ctx = c.getContext('2d')
        // 每20ms畫一次圖
        v.addEventListener('play', function () {
            var i = window.setInterval(function () {
                ctx.drawImage(v, 0, 0, 270, 135);
                if (v.ended) {
                    clearInterval(i)
                }
            }, 20)
        });
    </script>
</body>
</html>