1.首先安装依赖:
npm i html2canvas
2.uniap html样式
<view @click="test">进行拍摄</view>
<div>
<!-- 这里就是摄像头显示的画面 -->
<video id="video" width="400" height="300"></video>
<div>
<button @click="takePhone" style="margin-top: 10px;">拍照</button>
</div>
</div>
<div>图片截图画面</div>
<!-- 这里是点击拍照显示的图片画面 -->
<img :src="imgUrl" ></img>
</div>
3.uniapp 中js代码
import html2canvas from 'html2canvas'
data() {
return {
imgUrl:"",
blobFile: null,
canvas: null,
video:null,
mediaStreamTrack: '',
};
},
onShow() {
// 摄像头
this.video = document.querySelector('video');
},
methods: {
//点击拍照截图画面
takePhone() {
html2canvas(document.querySelector('video'), {
backgroundColor: null,
useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
}).then((canvas) => {
let url = canvas.toDataURL('image/png');
this.imgUrl = url;
})
},
test(){
var video = document.querySelector('video');
// 兼容代码
window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
//摄像头调用配置
var mediaOpts = {
audio: false,
video: { facingMode: "user"}
}
let that=this;
navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
that.mediaStreamTrack = stream;
video = document.querySelector('video');
if ("srcObject" in video) {
video.srcObject = stream
} else {
video.src = window.URL && window.URL.createObjectURL(stream) || stream
}
video.play();
}).catch(function (err) {
console.log(err)
});
},
}
2820

被折叠的 条评论
为什么被折叠?



