<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>拍照</title>
<style type="text/css">
position: absolute
left: 0
right: 0
top: 10px
margin: auto
background: white
display: none
}
</style>
</head>
<body style="text-align: center; margin: 0;">
<canvas id="canvas" style="position: absolute; top: -5000px;" width="1280" height="960"></canvas>
<video id="video" style="margin: 10px;"></video>
<canvas id="canvas-preview"></canvas>
<button id="takeIt" class="btn" onclick="takePicture()">拍照</button>
<button id="reClear" class="btn" onclick="reset()" style="display: none;">重拍</button>
<button id="upload" class="btn" onclick="uploadPhoto()" style="display: none;">上传</button>
</body>
<script type="text/javascript">
var w = window.innerWidth - 50, h = window.innerHeight - 50
var video = document.getElementById('video')
var preview = document.getElementById('canvas-preview')
var canvas = document.getElementById('canvas')
var takeIt = document.getElementById('takeIt')
var reClear = document.getElementById('reClear')
var upload = document.getElementById('upload')
video.style.width = "calc(100vw - 50px)", video.style.height = "calc(100vh - 50px)"
preview.width = w, preview.height = h
var previewCnt = preview.getContext('2d')
var context = canvas.getContext('2d')
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { //判断浏览器是否兼容
var constraints = {
audio: false,
video: {
width: w,
height: h
}
}
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
//请求摄像头权限,成功之后会返回媒体流stream
video.srcObject = stream
video.play()
}, function () { //获取摄像头权限失败的回调
alert("获取摄像头权限失败")
})
} else {
alert("当前浏览器不支持获取摄像头权限!")
}
/** * 拍照、canvas绘制 */
function takePicture() {
preview.style.display = "block"
takeIt.style.display = "none"
reClear.style.display = "unset"
upload.style.display = "unset"
previewCnt.drawImage(video, 0, 0, w, h)
context.drawImage(video, 0, 0, 1280, 960)
}
/**
* 重拍
*/
function reset() {
previewCnt.clearRect(0, 0, w, h)
context.clearRect(0, 0, 1280, 960)
preview.style.display = "none"
takeIt.style.display = "unset"
reClear.style.display = "none"
upload.style.display = "none"
}
/** * 上传图片 */
function uploadPhoto() {
var photo = window.location.href.split("?")[1]
var dataURL = canvas.toDataURL("image/jpeg")
eval( " window.opener."+photo+"(dataURL)")
window.close()
}
</script>
</html>