美文网首页
canvas实现视频播放

canvas实现视频播放

作者: 谢小逸 | 来源:发表于2017-06-14 17:19 被阅读0次
    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8">
        <title>Examples</title>
    </head>
    
    <body>
        <p> <a href="javascript:;" class="playBtn2" style="display: block;width:100px; background: #222;color:#fff; line-height: 40px; text-align: center;margin:14px 0">点击播放</a></p>
        <div class="videoBox">
            <canvas id="canvas2" width="640" height="1640"></canvas>
            <p></p>
            <div class="load" id="loadWrap2" style="display: none;">
                <div class="loading2"></div>
            </div>
        </div>
        <script type="text/javascript">
        var imgArr = [],
            source = {},
            now2 = 0,
            imgNum = 0,
            timer = null;
        var canvas2 = document.querySelector('#canvas2');
        var videoBox = document.querySelector('.videoBox');
        var view = {
            w: videoBox.offsetWidth,
            h: videoBox.offsetHeight
        }
        canvas2.width = view.w;
        canvas2.height = view.h;
        var ctx = canvas2.getContext("2d");
        ctx.clearRect(0, 0, canvas2.width, canvas2.height);
    
        //添加图片进数组
        function pushImgArr(num) {
            document.querySelector('#loadWrap2').style.display = 'block';
            imgArr = [];
            for (var i = 1; i < num; i++) {
                imgArr.push('videoImg/' + i + '.jpg');
            };
            imgLoad();
        };
    
        //图片加载
        function imgLoad() {
            source['src' + now2] = new Image();
            source['src' + now2].src = imgArr[now2];
            source['src' + now2].onload = function() {
                now2++;
                if (now2 > imgArr.length - 1) {
                    //加载成功
                    document.querySelector('#loadWrap2').style.display = 'none';
                    //执行canvas渲染
                    movieInit()
                } else {
                    //递归加载
                    imgLoad();
                };
            };
        };
    
        //canvas图片渲染
        function movieInit() {
            clearInterval(timer);
            timer = setInterval(function() {
                if (imgNum == imgArr.length) {
                    clearInterval(timer);
                } else {
                    ctx.clearRect(0, 0, canvas2.width, canvas2.height);
                    ctx.drawImage(source['src' + imgNum], 0, 0, view.w, view.h);
                    imgNum++;
                };
            }, 200);
        };
    
        //按钮点击开始播放
        document.querySelector('.playBtn2').onclick = function() {
            pushImgArr(25);
        };
        </script>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:canvas实现视频播放

          本文链接:https://www.haomeiwen.com/subject/afheqxtx.html