js截取视频封面

2019-09-12 12:27:45

有些事情用前端来做肯定比后端来得实在! 来吧,直接上代码吧!

<html>
<body>
<input type="file" onchange="window.videoApp.method.fieldChange(this)" accept="video/*">
<img src="" id="imgTest" />
<script>
    window.addEventListener('DOMContentLoaded', function () {

        // 获取文件
        var app = {
            data: {
                imageData: null,
            },
            method: {
                fieldChange: function fieldChange(file) {
                    if (file.files.length) {
                        if (file && file.type.indexOf('video/') == 0) {
                            app.method.getVideoImg(URL.createObjectURL(file),function (imageData) {
                                document.getElementById('imgTest').src = imageData.url;
								app.data.imageData = imageData;
                            });
                        }
                    }
                    file.value = null;
                },
                getVideoImg: function (VideoUrl, callback) {
                    let video = document.createElement('video');
                    video.setAttribute('crossOrigin', 'anonymous');
                    video.src = VideoUrl;
                    video.addEventListener('loadeddata', function () {
                        let width = this.videoWidth;
                        let height = this.videoHeight;
                        let canvas = document.createElement('canvas');
                        let ctx = canvas.getContext('2d');
                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
                        var image = {
                            url: canvas.toDataURL('image/jpeg', 1),
                            width: width,
                            height: height,
                            currentTime: this.currentTime,
                            duration: this.duration
                        };
                        canvas.toBlob(function (blob) {
                            image.blob = blob;
                            typeof callback == 'function' && callback(image);
                        });
                    });
                }
            }
        };
        window.videoApp = app;
    });

</script>
</body>
</html>

·

可以直接在控制台测试:

window.videoApp.method.getVideoImg( "http://asdsadsa.mp4",function(imageData){
	document.getElementById('imgTest').src = imageData.url;
});
本文由"putyy"原创,转载无需和我联系,但请注明来自putyy
您的浏览器不支持canvas标签,请您更换浏览器