js+HTML5+canvas实现video视频截图(帧)的方法(截取1-9秒的帧)

一、 上传视频拿到视频地址

上传代码略了,特么自己写吧。

二、拿到地址截图

this.$nextTick(() => {
    let load = layer.load();
    let video = document.createElement("video");
    let source = document.createElement("source");
    source.src = that.media;
    source.type = "video/mp4";
    video.appendChild(source);
    let canvas = document.createElement("canvas");
    canvas.width = that.width;
    canvas.height = that.height;
    // 设置video允许跨域
    video.setAttribute('crossOrigin', 'anonymous');
    let ctx = canvas.getContext("2d");
    that.posters = [];
    // 从1 - 9秒 设置视频时长 截图
    video.currentTime = 1;
    let duration = that.duration;
    //监听设置进度时长 1 -9 秒 每秒截一张图
    video.addEventListener("timeupdate", function () {
        ctx.drawImage(video, 0, 0, that.width, that.height);
        // 画板转为base64图片
        that.posters.push(canvas.toDataURL());
        that.poster = that.posters[0];
        if (video.currentTime < (duration < 10 ? duration : 9)) {
            video.currentTime = video.currentTime + 1;
        }
        if (video.currentTime == 9 || duration == video.currentTime) {
            layer.close(load);
            // 选择截图上传
            vm.selectCut();
        }
    });
});

三、选择一张截图上传作为封面

//data 选择的base64图片数据
//filename 图片名称
// 此方法是将base64图片转为file对象,可以通过Ajax直接上传
base64datatoFile(data, filename) {
    var arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type: mime});
}

四、上传图片

var formData = new FormData();
    const file = vm.base64datatoFile(vm.cutData, '视频截图.png');
    formData.append("file", file);
    $.ajax({
        url: '上传图片地址',
        method: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (res) {
            //解析json
            vm.poster = res.result.url;
            layer.close(index);
            layer.close(load);
        }
});
# html   js   前端  

评论

企鹅群:39438021

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×