最近有个场景是,在页面中需要展示一个视频,希望截取视频首帧为图片做封面。
先上代码:
/**
* @param {string} src
*
* canvas.toBlob(),canvas.toDataURL("image/png")等方法要求canvas和video/image同域,否则会报错
* 目前已经让运维添加video.40017.cn跨域支持
* https://developer.mozilla.org/zh-CN/docs/Web/HTML/CORS_enabled_image
*/
function uploadFirstframe(src) {
var videoSrc = (src && /video\.40017\.cn/.test(src)) ? src : "";
//video2Canvas
function videoToCanvas(src, callback) {
var video = document.createElement("video");
video.crossOrigin = "anonymous";
video.src = src;
//第一帧加载完成事件
video.onloadeddata = function () {
var scale = 0.5; //缩放
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
callback && callback(canvas)
};
}
if (videoSrc) {
videoToCanvas(videoSrc, function (canvas) {
if (canvas) {
//图片预览
var output = document.getElementById("output");
var img = document.createElement("img");
var src = canvas.toDataURL("image/png");
img.src = canvas.toDataURL("image/png");
output.appendChild(img);
//上传首帧图片
canvas.toBlob(function (blob) {
// 图片ajax上传
var formData = new FormData();
formData.append("file", blob, "aa.png");
axios.post(
'上传地址',
formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
}
});
} else {
//错误处理,上传一张默认图片?
console.log('error')
}
}
uploadFirstframe('https://video.40017.cn/jingqu/20180515/649B4DE91C781C0B.mp4');
核心代码是canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
,canvas的drawImage方法是可以接收video元素作为参数的。参考:drawImage。所以就简单了,先把video转成canvas,再通过canvas.toDataURL()
和canvas.toBlob()
来实现图片预览和上传。
ps:有一个小坑爹的地方是:canvas.toBlob()
,canvas.toDataURL("image/png")
等方法要求canvas和video/image同域,否则会报错。可以通过设置cors来解决。
网友评论