微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript 方向 API 不适用于移动设备

如何解决JavaScript 方向 API 不适用于移动设备

我想移动球的例子来自:

https://developer.mozilla.org/en-US/docs/Web/Events/Detecting_device_orientation

我试图使用加速度计或陀螺仪。 mozilla 的演示在我的手机上运行。 我的演示不能在同一部手机上运行 - 所以我认为它的代码失败了。 不知道为什么它不起作用。 我的示例链接

http://serwer2134873.home.pl/tests/orientation/index.html

所以我创建了相同的代码

    <head>
        <Meta charset="utf-8">
        <style type="text/css">

            svg:not(:root) {
              display: block;
            }

            .playable-code {
              background-color: #f4f7f8;
              border: none;
              border-left: 6px solid #558abb;
              border-width: medium medium medium 6px;
              color: #4d4e53;
              height: 100px;
              width: 90%;
              padding: 10px 10px 0;
            }

            .playable-canvas {
              border: 1px solid #4d4e53;
              border-radius: 2px;
            }

            .playable-buttons {
              text-align: right;
              width: 90%;
              padding: 5px 10px 5px 26px;
            }
            .garden {
  position: relative;
  width : 200px;
  height: 200px;
  border: 5px solid #CCC;
  border-radius: 10px;
}

.ball {
  position: absolute;
  top   : 90px;
  left  : 90px;
  width : 20px;
  height: 20px;
  background: green;
  border-radius: 100%;
}

        </style>
        
        <title>Detecting device orientation - Orientation_example - code sample</title>
    </head>
    <body>
<div class="garden">
  <div class="ball"></div>
</div>

<pre class="output"></pre>

        
        
            <script>
                var ball   = document.querySelector('.ball');
var garden = document.querySelector('.garden');
var output = document.querySelector('.output');

var maxX = garden.clientWidth  - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
  var x = event.beta;  // In degree in the range [-180,180)
  var y = event.gamma; // In degree in the range [-90,90)

  output.textContent  = `beta : ${x}\n`;
  output.textContent += `gamma: ${y}\n`;

  // Because we don't want to have the device upside down
  // We constrain the x value to the range [-90,90]
  if (x >  90) { x =  90};
  if (x < -90) { x = -90};

  // To make computation easier we shift the range of
  // x and y to [0,180]
  x += 90;
  y += 90;

  // 10 is half the size of the ball
  // It center the positioning point to the center of the ball
  ball.style.top  = (maxY*y/180 - 10) + "px";
  ball.style.left = (maxX*x/180 - 10) + "px";
}

window.addEventListener('deviceorientation',handleOrientation);

            </script>
        
    </body>

解决方法

需要 SSL 连接协议 (https)。 没想到:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。