您的浏览器不支持canvas标签,请您更换浏览器

js截取视频封面

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

<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;
});

LW放下的博客
请先登录后发表评论
  • latest comments
  • 总共0条评论