<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="video" style="width: 400; height: 300;"></div>
<div>
<button id="capture">拍照</button>
</div>
<canvas id="canvas" width="400" height="300"></canvas>
<script>
function getUserMedia(constraints, success, error){
if(navigator.mediaDevices.getUserMedia){
//最新的api
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
} else if (navigator.webkitGetUserMedia){
// web 核心浏览器
navigator.webkitGetUserMedia(constraints,success,error);
} else if (navigator.mozGetUserMedia){
//Firefox浏览器
navigator.mozGetUserMedia(constraints,success,error);
} else if (navigator.getUserMedia){
// 旧版api
navigator.getUserMedia(constraints,success,error);
}
}
let video = document.getElementById("video");
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
function success(stream){
//兼容webkit核心浏览器
let CompatibleUrl = window.URL || window.webkitURL;
//讲视频流设为video元素的源
video.src = CompatibleUrl.createObjectURL(stream);
video.paly();//播放视频
}
function error(error){
console.log('方位媒体设备失败:', error.name,error.message);
}
if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia){
getUserMedia({video:{ width: 400, height: 300}}, success, error);
} else {
alert('你的浏览器不只是访问媒体设备');
}
// 绑定单击事件
document.getElementById('capture').addEventListener("click", function(){
context.drawImage(video,0,0,400,300)
},false)
</script>
<script>
// 方向事件:deviceorientation
// 移动事件: devicemotion
// 摇一摇实例
const SHKE_SPEED_THRESHOLD = 300;
let lastTime = 0; //上传变化的时间
let x = y = z = lastX = lastY = LastZ = 0;
function motionHandler(event){
let acceleration = event.accelerationIncludingGravity;
let curTime = Date.now();
if ((curTime - lastTime) > 120){
let diffTime = curTime - lastTime;
lastTime = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
}
}
if (window.DeviceMOtionEvent) {
window.addEventListener('devicemotion', motionHandler, false);
} else {
alert('你的设备不支持位置感应');
}
</script>
</body>
</html>