<!doctype html> <html> <head> <meta charset="gbk"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <style> .test{ border:2px solid green; width:300px; height:350px; background: #000; position: relative; COLOR:#FFF; } .test #ball{ width:12px; height:12px; background: #fff; -webkit-border-radius:6px; position: absolute; left:0; right: 0; } </style> </head> <body> <h2>设备方向感应测试</h2> <div id="msg"></div> <div id='test' tabindex='0' class="test"> <!--<img src="img/3.png" id="ball">--> <div id="ball"></div> </div> <script> function Orientation(selector){} Orientation.prototype.init = function(){ window.addEventListener('deviceorientation', this.oriListener, false); window.addEventListener('MozOrientation', this.oriListener, false); //为firefox所用 window.addEventListener('devicemotion', this.oriListener, false); //重力感应 } Orientation.prototype.oriListener = function(e) { setTimeout(function(){ handler(e); deviceMotionHandler(e) },10); function handler(e){ // For FF3.6+ if (!e.gamma && !e.beta) { // angle=radian*180.0/PI 在firefox中x和y是弧度值, e.gamma = (e.x * (180 / Math.PI)); //转换成角度值, e.beta = (e.y * (180 / Math.PI)); //转换成角度值 e.alpha = (e.z * (180 / Math.PI)); //转换成角度值 } /* beta: -180..180 (rotation around x axis) */ /* gamma: -90..90 (rotation around y axis) */ /* alpha: 0..360 (rotation around z axis) (-180..180) */ var gamma = e.gamma var beta = e.beta var alpha = e.alpha if(e.accelerationIncludingGravity){ // window.removeEventListener('deviceorientation', this.orientationListener, false); gamma = e.accelerationIncludingGravity.x*300 beta = -e.accelerationIncludingGravity.y*300 alpha = event.accelerationIncludingGravity.z*300 } if (this._lastGamma != gamma || this._lastBeta != beta) { document.querySelector("#msg").innerHTML = "x: "+ beta.toFixed(2) + " y: " + gamma.toFixed(2) + " z: " + (alpha != null?alpha.toFixed(2):0) var style = document.querySelector("#ball").style; style.left = gamma/90 * 200 + 150 +"px"; style.top = beta/90 * 200 + 100 +"px"; this._lastGamma = gamma; this._lastBeta = beta; } } function deviceMotionHandler(e) { /* if(e.accelerationIncludingGravity){ var gx = e.accelerationIncludingGravity.x; var gy = e.accelerationIncludingGravity.y; var gz = e.accelerationIncludingGravity.z; } var facingUp = -1; if (gz > 0) { facingUp = +1; } var tiltLR = Math.round(((gx) / 9.81) * -90); var tiltFB = Math.round(((gy + 9.81) / 9.81) * 90 * facingUp); //document.getElementById("moCalcTiltLR").innerHTML = tiltLR; // document.getElementById("moCalcTiltFB").innerHTML = tiltFB; var rotation = "rotate(" + tiltLR + "deg) rotate3d(1,0,0, " + (tiltFB) + "deg)"; document.getElementById("imgLogo").style.webkitTransform = rotation; */ var gamma = e.gamma var beta = e.beta var alpha = e.alpha var tiltLR =gamma; //Math.round(((beta) / 9) * -90); var tiltFB = beta; var rotation = "rotate(" + tiltLR + "deg)"; var rotation2 = "rotate(" + tiltFB + "deg)"; var style = document.querySelector("#imgLogo").style; var style2 = document.querySelector("#imgLogo2").style; style.webkitTransform = rotation; style2.webkitTransform = rotation2; } }; (new Orientation()).init(); </script> </body> </html>
扩展:微信小程序链接:http://www.wxappclub.com/doc/1-43
H5监听摇一摇和手机倾斜事件(重力感应)
属性 | 释义 |
---|---|
event.accelaration | x(y,z):设备在x(y,z)方向上的移动加速度值 |
event.accelarationIncludingGravity | x(y,z):考虑了重力加速度后设备在x(y,z)方向上的移动加速度值 |
event.rotationRate | alpha,beta,gamma:设备绕x,y,z轴旋转的角度 |
var shakeThreshold = 1000; // 定义一个摇动的阈值
var lastUpdate = 0; // 记录上一次摇动的时间
var x, y, z, lastX, lastY, lastZ; // 定义x、y、z记录三个轴的数据以及上一次触发的数据
// 监听传感器运动事件
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
//浏览器不支持DeviceMotion
alert('天呐,你的手机竟然还不支持摇一摇ヾ(◍°∇°◍)ノ゙');
}
// 运动传感器处理
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity; // 获取含重力的加速度
var curTime = new Date().getTime();
// 100毫秒进行一次位置判断
if ((curTime - lastUpdate) > 100) {
var diffTime = curTime - lastUpdate;
lastUpdate = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
if (speed > shakeThreshold) {
alert("摇一摇触发")
}
lastX = x;
lastY = y;
lastZ = z;
}
}
- 重力感应方向控制(DeviceOrientation)——个人测试这里使用过
-
属性 释义 alpha 设备指示的方向,根据指南针的设定情况而定 beta 设备绕x轴旋转的角度 gamma 设备绕y轴旋转的角度 工作原理 :
根据event对象的三个方向的参数来确定设备的旋转角度。其中,alpha的取值范围是0-360,这个需要根据设备的指南针设定情况而定,一般来说,设备指向正北方向时为0.beta值为设备绕x轴旋转的角度,取值范围为-180-180。gamma取值范围-90-90.
这里面alpha值的意义并不大,主要参考beta和gamma值。
当屏幕从水平沿y轴向左倾斜时gamma值变为负值,向右倾斜变为正值。
当屏幕从水平沿x轴向前倾斜时beta值变为正值,向后倾斜时变为负值。
所以,如果我们设定一个阈值,当beta和gamma的绝对值大于这个阈值时,我们就认为设备发生了旋转。另外根据beta和gamma的值来判断向左倾斜还是向右倾斜,以及倾斜的程度。
// 绑定deviceorientation事件和处理程序
if(window.DeviceOrientationEvent){
window.addEventListener('deviceorientation',DeviceOrientationHandler,false);
}else{
alert("您的浏览器不支持DeviceOrientation");
}
function DeviceOrientationHandler(event){
var alpha = event.alpha,beta = event.beta,gamma = event.gamma;
if(alpha != null || beta != null || gamma != null){
//各个方向旋转的值
//alert("alpha:" + alpha + "<br />beta:" + beta + "<br />gamma:" + gamma)
//判断屏幕方向
if( gamma > 0 ){
alert("向右倾斜");
}else{
alert("向左倾斜");
}
}
}
DeviceOrientationEvent是获取方向,得到device静止时的绝对值; DeviceMotionEvent是获取移动速度,得到device移动时相对之前某个时间的差值比 设备定位API,该API允许你收集设备的方向和移动信息。此外,该API只在具备陀螺仪功能的设备上使用。 <html> <head> <title>DeviceOrientationEvent</title> <meta charset="UTF-8" /> </head> <body> <p>左右:<span id="alpha">0</span> </p> <p>前后:<span id="beta">0</span> </p> <p>扭转:<span id="gamma">0</span> </p> <p>指北针指向:<span id="heading">0</span>度</p> <p>指北针精度:<span id="accuracy">0</span>度</p> <hr /> <p>x轴加速度:<span id="x">0</span>米每二次方秒</p> <p>y轴加速度:<span id="y">0</span>米每二次方秒</p> <p>z轴加速度:<span id="z">0</span>米每二次方秒</p> <hr /> <p>x轴加速度(考虑重力加速度):<span id="xg">0</span>米每二次方秒</p> <p>y轴加速度(考虑重力加速度):<span id="yg">0</span>米每二次方秒</p> <p>z轴加速度(考虑重力加速度):<span id="zg">0</span>米每二次方秒</p> <hr /> <p>左右旋转速度:<span id="Ralpha">0</span>度每秒</p> <p>前后旋转速度:<span id="Rbeta">0</span>度每秒</p> <p>扭转速度:<span id="Rgamma">0</span>度每秒</p> <hr /> <p>上次收到通知的间隔:<span id="interval">0</span>毫秒</p> <script type="text/javascript"> function orientationHandler(event) { document.getElementById("alpha").innerHTML = event.alpha; document.getElementById("beta").innerHTML = event.beta; document.getElementById("gamma").innerHTML = event.gamma; document.getElementById("heading").innerHTML = event.webkitCompassHeading; document.getElementById("accuracy").innerHTML = event.webkitCompassAccuracy; } function motionHandler(event) { document.getElementById("interval").innerHTML = event.interval; var acc = event.acceleration; document.getElementById("x").innerHTML = acc.x; document.getElementById("y").innerHTML = acc.y; document.getElementById("z").innerHTML = acc.z; var accGravity = event.accelerationIncludingGravity; document.getElementById("xg").innerHTML = accGravity.x; document.getElementById("yg").innerHTML = accGravity.y; document.getElementById("zg").innerHTML = accGravity.z; var rotationRate = event.rotationRate; document.getElementById("Ralpha").innerHTML = rotationRate.alpha; document.getElementById("Rbeta").innerHTML = rotationRate.beta; document.getElementById("Rgamma").innerHTML = rotationRate.gamma; } if (window.DeviceMotionEvent) { window.addEventListener("devicemotion", motionHandler, false); } else { document.body.innerHTML = "What user agent u r using???"; } if (window.DeviceOrientationEvent) { window.addEventListener("deviceorientation", orientationHandler, false); } else { document.body.innerHTML = "What user agent u r using???"; }; </script> </body>
</html>
<!DOCTYPE html> <html> <head> <title>compass</title> <style type="text/css"> html,body{ margin: 0; height: 100%; display: flex; align-items: center; justify-content: center; } #compass{ width: 50vw; height: 50vw; transform-origin:center center; border-radius: 50vw; overflow: hidden; border: 10px double #333; } .compass-inner{ margin: auto; height: 100%; width: 10vw; position: relative; } .compass-inner::before{ content: ""; display: block; left: 0; top: 0; height: 0; width: 0; border: 25vw solid red; border-width: 0 5vw 25vw 5vw; border-color: transparent transparent red transparent; } .compass-inner::after{ content: ""; display: block; left: 0; bottom: 0; height: 0; width: 0; border: 25vw solid blue; border-width: 25vw 5vw 0 5vw; border-color: blue transparent transparent transparent; } </style> </head> <body> <div id="compass"> <div class="compass-inner"></div> </div> <script type="text/javascript"> var compass = document.getElementById('compass'); if(window.DeviceOrientationEvent) { window.addEventListener('deviceorientation', function(event) { var alpha; if(event.webkitCompassHeading) { //iOS alpha = event.webkitCompassHeading; compass.style.WebkitTransform = 'rotate(-' + alpha + 'deg)'; show.innerHTML = alpha; } else { alpha = event.alpha; webkitAlpha = alpha; if(!window.chrome) { webkitAlpha = alpha-270; } } compass.style.Transform = 'rotate(' + alpha + 'deg)'; compass.style.WebkitTransform = 'rotate('+ webkitAlpha + 'deg)'; compass.style.MozTransform = 'rotate(-' + alpha + 'deg)'; }, false); }else{ document.querySelector('body').innerHTML = '浏览器不支持陀螺仪'; } </script> </body> </html>
具体解释下三个量:
aplha
装置水平放置时,绕 Z 轴旋转的角度,数值为 0 度到 360 度。
beta
行动装置水平放置时,绕 X 轴旋转的角度,数值为 -180 度到 180 度。
gamma
行动装置水平放置时,绕 Z 轴旋转的角度,数值为 -90 度到 90 度。
HTML5新API—重力感应器(摇一摇)
当我们的设备“位置”发生变化时,会在devicemotion的事件对象(ev)内保存相关信息,我们从其中获取我们所需要的信息即可。 首先我们要判断下我们的设备是否支持DeviceMotionEvent if(window.DeviceMotionEvent){ alert('ok,可以支持');} else { alert('不支持'); } 接下来我们就可以通过devicemotion事件(注意此处必须用事件绑定,必须用事件绑定必须用事件绑定),然后通过ev下的accelerationIncludingGravity来获取X、Y、Z的相关参数: if(window.DeviceMotionEvent){ window.addEventListener('devicemotion',function(ev){ //当触发devicemotion事件后查看相关信息 var acc = ev.accelerationIncludingGravity; alert('x坐标:'+acc.x+'--y坐标:'+acc.y+'---z坐标:'+acc.z); },false); } 下面我们就开始,编写一个简单的微信摇一摇功能 当我们手机端X方向或Y方向或Z方向,就触发摇一摇功能 利用CSS3的动画来给box一个随机的背景色 html布局: <div id="box"></div> 简单的为box设置点样式: <style type="text/css" media="screen"> //定义一个左右摇摆动画 @keyframes test{ 0%{ transform:rotate(0deg); } 25%{ transform:rotate(30deg); } 50%{ transform:rotate(0deg);} 75%{ transform:rotate(-30deg); } 100%{ transform:rotate(0deg);} } #box{ width:400px;height:200px; background:red; margin:200px auto; } //给box加一个动画 #box.shake{ animation:200ms test ease; } </style> 接下来我们就用JS获取信息没然后操作BOX的颜色与位置变化 //在这里定义一个随机数函数 function rnd(m,n){ return parseInt(Math.random()*(n-m)+m); } //给文档加DOMContentLoaded事件,该事件类似window.onloaded document.addEventListener('DOMContentLoaded',function(){ var oBox = document.getElementById('box'); var timer=null; if(window.DeviceMotionEvent){ window.addEventListener('devicemotion',function(ev){ var acc = ev.accelerationIncludingGravity; //获取devicemotion的xyz变化 var x = acc.x; var y = acc.y; var z = acc.z; if( x>30|| y>30|| z>30 ){ oBox.className ='shake'; 、 oBox.style.background='rgb('+rnd(0,256)+','+rnd(0,256)+','+rnd(0,256)+')'; timer=setTimeout(function(){ oBox.className =''; },300) } },false); }else{ alert('不支持'); } },false); 转链接:https://www.jianshu.com/p/6dcb963a58dd