访问纯JavaScript中的设备方向

2021-03-08 00:59:07

在JavaScript中,您可以通过侦听DeviceRientation事件来访问您的设备方向数据。它与以下内容一样简单:

窗户 。 addeventlistener(' leviceorientation' speedorientation);函数手提琴(事件){const alpha =事件.alpha; const beta =事件.beta; const gamma =事件.gamma; // 做东西... }

但!并非每个浏览器都允许您访问没有用户的方向数据' s权限。例如,IOS 13 Apple已介绍了RequestPermission方法。必须在用户操作(单击,点击或等效)上触发它。

函数onclick(){if(typefemotionevent .requestpermission ==='函数'){//处理iOS 13+设备。 devicemotionevent。 RequestPermission()。然后((state)=> {if(state ==='授予#39;){window。addeventlistener(' devicemotion',spearorientation);} else {console。错误(&# 39;访问取向的请求被拒绝');}})。 catch(控制台.Error); } else {//处理常规非IOS 13+设备。窗户 。 AddeventListener(' devicemotion',spearorientation); }}

尝试在下面打开切换,看看您的设备报告的角度值。

如果您'使用桌面设备,您可以模仿&#34的设备旋转;传感器" Dev-Tools中的选项卡:

凉爽的!所以现在我们可以访问设备方向,我们甚至可以在浏览器中测试它!

我想要采取的最后一步就是想出反应钩子,它将封装对我提取的方向,并使它更容易在反应组件中使用它(就像上面向您展示的角度一样。

导入{USECALLBACK,USEEFFECT,USESTATE}从' React' ; type = {alpha:number | null,beta:数字| NULL,伽玛:号码| null,} type = {方向:loborientation | null,错误:错误| null,请求手柄:()=>承诺<布尔> ,Revokeacess:()=>承诺<空隙> ,};导出const imbuseviceorientation =():moreedeviceorientationdata => {const [错误,setError] = useState(null); const [方向,setorientation] = usestate(null); const ondeviceorientation =(事件:deviceorientationEvent):Void => {setorientation({alpha:事件.alpha,beta:事件.beta,gamma:事件.gamma,}); }; const revokeaccessasync = async():promise<空隙> => { 窗户 。 RemoveeventListener(' Leviceorientation',ondeviceorientation); Setorientation(NULL); }; Const RequestAccessAsync = Async():promise<布尔> => {if(!deviceorientationEvent){setError('您的浏览器不支持设备方向事件'));返回false; }如果(deviceOrientationEvent .requestpermission&& typefofemotionevent .requestpermission ==='函数'){让许可:permisionstate;尝试{权限=等待deviceorientationEvent。索赔();捕获(错误){setError(错误);返回false; }如果(许可!=='授予'){setError('请求访问设备方向拒绝'));返回false; } } 窗户 。 AddeventListener(' leviceorientation',ondeviceorientation);返回真; }; Const RequestAccess = USECALLBACK(RequestAccessAsync,[]); Const RevokeAccess = USECALLBACK(RevokeAccessAsync,[]); Usefeffect(()=> {return():void => {Revokeaccess();};},[Revokeaccess]);返回{方向,错误,requestAccess,RevokeAccess,}; };

导入从&#39反应;反应' ;从&#39导入切换; ./切换' ;从&#39导入{mundereviceorientation}; ./ hilderviceorientation' ; Const OrientationInfo =():反应。 Reactelement => {const {方向,RequestAccess,RevokeAccess,Error} = UnderViceOrientation(); const ontoggle =(togglestate:boolean):void => {const结果= togglestate? RequestAccess():RevokeAccess(); }; Const OrientationInfo =定向&& (ɑ:{取向.alpha}β:{方向.beta}γ:{方向.gamma}); const ergenElement =错误? ({错误.message}):null;返回({OrientationInfo} {ErroreLement}); };导出默认方向inInfo;

最后,可以访问设备方向,让&#39模仿3D空间,通过旋转移动设备,可以从3D透视图中查看对象的可能性。想象一下,你有一个虚拟的购物项目,你想在把它放入篮子之前从不同的角度和侧面看到它。

我们将使用一个简单的3D多维数据集,通过使用透视图,透视 - 原点和变换属性使用纯CSS(您可以在CSS-Tricks.com上找到具有样式的完整示例)。

在这里,我们走了,这是我们的Gyro-Cube,你应该能够根据您的设备方向看出不同的角度!

您可以在Trekhleb.github.io Repo中找到本文(包括Gyro-Cube样式)的所有代码示例。

如果您'从笔记本电脑阅读文章,在这里'演示如何在移动设备上工作: 我希望这个例子对你很有用! 我也希望您将提出更有趣和更现实的用例,而不是上面的陀螺立方体g快乐编码!