检测 html5 移动中的抖动 [英] Detecting shaking in html5 mobile

查看:22
本文介绍了检测 html5 移动中的抖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用 html5 构建一个网络应用程序,它需要能够检测用户何时晃动手机以及晃动手机的速度.我一直在浏览,但似乎找不到任何关于如何实现这一点的例子.我知道 html5 有一个可以检测手机方向的加速度计,但它如何检测用户摇晃手机的速度?

I'm building a web app in html5 at the moment that needs to be able to detect when the user shakes their phone and how fast they are shaking it. I've been browsing around but can't seem to find any examples of how I could implement this. I know html5 has an accelerometer that can detect the orientation of the phone, but how does it detect the speed at which the user is shaking it?

我也在我的 iPhone 上测试这个,虽然理想情况下我希望它也能在 Android 设备上运行.想法?例子也会很棒.谢谢!

Also I'm testing this on my iPhone, although ideally I would like it to work on Android devices too. Thoughts? Examples would be great too. Thanks!

推荐答案

shake.js 看起来是一个很好的库 - 它提供了一个自定义的 'shake' 事件并且在现代浏览器上受支持.这是一个关于如何实现它的他们文档中的示例设置:

shake.js looks to be a good library for this - it provides a custom 'shake' event and is supported on modern browsers. Here's an example setup from their documentation on how you could implement it:

<script src="shake.js"></script>
<script>
var myShakeEvent = new Shake({
    threshold: 15, // optional shake strength threshold
    timeout: 1000 // optional, determines the frequency of event generation
});

// Start listening to device motion
myShakeEvent.start(); 

// Register a shake event listener on window with your callback
window.addEventListener('shake', shakeEventDidOccur, false); 

//function to call when shake occurs
function shakeEventDidOccur () {

    //put your own code here etc.
    alert('shake!');
}
</script>

请注意,在不安全的浏览上下文(例如 http://)中,这在某些浏览器中不起作用

Note that this does not work in some browsers when in an insecure browsing context (eg. http://)

这篇关于检测 html5 移动中的抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆