canvas实现视频播放

2017-06-14  本文已影响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>
上一篇下一篇

猜你喜欢

热点阅读