uniapp (截取视频第一帧图片)
【代码】uniapp (截取视频第一帧图片)
·
<template>
<view :prop="newVal" :change:prop="canvas.getVideoCanvas"></view>
</template>
<script>
export default {
data(){
return {
newVal: null,//视频地址
},
methods:{
// 逻辑层拿到base64字符串,上传网络图片
getBase64(options) { //监听事件
console.log(options, '=======options========');
// this.request({
// url: 'common/base64', //仅为示例,非真实的接口地址
// data: {
// base64: options.base64
// }
// }).then(res=>{
// // 拿到上传base64图片的网络图片
// console.log(res)
// })
},
}
}
</script>
<!-- 视图层script module对应HTML代码中view的id-->
<script module="canvas" lang="renderjs">
export default {
methods: {
// 视图层创建base64图片
// 视频截图封面图
getVideoCanvas(newValue, oldValue, ownerInstance) {
console.log(newValue,"==============newValue=============")
if(!newValue){
return false
}
// 在缓存中创建video标签
var video = document.createElement("VIDEO")
// 通过setAttribute给video dom元素添加自动播放的属性,因为视频播放才
// 能获取封面图
video.setAttribute('autoplay', 'autoplay')
// 再添加一个静音的属性,否则自动播放会有声音
video.setAttribute('muted', 'muted')
// 上面我们只是创建了video标签,视频播放需要内部的source的标签,scr为
// 播放源
video.innerHTML = '<source src=' + newValue + ' type="audio/mp4">'
// 再创建canvas画布标签
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// video注册canplay自动播放事件
video.addEventListener('canplay', function () {
// 创建画布的宽高属性节点,就是图片的大小,单位PX
var anw = document.createAttribute("width");
anw.nodeValue = 500;
var anh = document.createAttribute("height");
anh.nodeValue = 300;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
// 画布渲染
ctx.drawImage(video, 0, 0, 500, 300);
// 生成图片
var base64 = canvas.toDataURL('image/png') // 这就是封面图片的base64编码
// 视频结束播放的事件
video.pause()
// 传递数据给逻辑层
ownerInstance.callMethod('getBase64',{ //注册事件
base64: base64
})
}, false)
}
}
}
</script>
更多推荐
已为社区贡献9条内容
所有评论(0)