如何让 DeviceOrientationEvent 和 DeviceMotionEven上工作?

我正在尝试在我的网站上实现 DeviceOrientationEvent 和 DeviceMotionEvent 以获得 3D 效果。但是,控制台不会记录任何信息,显然 iOS 13 需要用户设置权限才能开始执行此操作。我似乎无法弄清楚如何正确设置它。


我做了一些研究,这就是我发现的:https : //github.com/w3c/deviceorientation/issues/57#issuecomment-498417027


可悲的是,在线提供的所有其他方法都不再可用。


window.addEventListener('deviceorientation', function(event) {

    console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);

});

我收到以下错误消息:


[警告] 在请求并授予许可,触发设备运动或方向事件。


精慕HU
浏览 316回答 3
3回答

翻翻过去那场雪

if ( location.protocol != "https:" ) {location.href = "https:" + window.location.href.substring( window.location.protocol.length );}function permission () {    if ( typeof( DeviceMotionEvent ) !== "undefined" && typeof( DeviceMotionEvent.requestPermission ) === "function" ) {        // (optional) Do something before API request prompt.        DeviceMotionEvent.requestPermission()            .then( response => {            // (optional) Do something after API prompt dismissed.            if ( response == "granted" ) {                window.addEventListener( "devicemotion", (e) => {                    // do something for 'e' here.                })            }        })            .catch( console.error )    } else {        alert( "DeviceMotionEvent is not defined" );    }}const btn = document.getElementById( "request" );btn.addEventListener( "click", permission );使用页面上的元素作为事件触发器并为其指定“请求”ID。这将检查 https 并在请求 API 授权之前根据需要进行更改。昨天找到这个,但不记得网址。

喵喔喔

从 iOS 13 beta 2 开始,您需要调用 DeviceOrientationEvent.requestPermission() 来访问陀螺仪或加速度计。这将显示一个权限对话框,提示用户允许此站点的运动和方向访问。请注意,如果您尝试在页面加载时自动调用它,这将不起作用。用户需要采取一些操作(如点击按钮)才能显示对话框。此外,当前的实现似乎要求该站点启用 https。

慕的地6264312

您需要单击或用户手势来调用 requestPermission()。像这样 :<script type="text/javascript">&nbsp; &nbsp; function requestOrientationPermission(){&nbsp; &nbsp; &nbsp; &nbsp; DeviceOrientationEvent.requestPermission()&nbsp; &nbsp; &nbsp; &nbsp; .then(response => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (response == 'granted') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.addEventListener('deviceorientation', (e) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do something with e&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .catch(console.error)&nbsp; &nbsp; }</script><button onclick='requestOrientationPermission();'>Request orientation permission</button>注意:如果您在权限提示上单击取消并想再次测试它,您需要退出 Safari 并重新启动它以让提示返回。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript