新年不是搞了个摇签的功能吗,弹幕效果我们前面讲过了,今天来讲说摇一摇效果html
完整 DEMO前端
html 5 提供了一些方法在移动端得到设备方向及运动(由于他是依赖传感器硬件的,pc 没有也不存在抱着台式机跑来跑去场景)。传感器包括陀螺仪、加速器和磁力仪(罗盘)。vue
能够实现什么效果?segmentfault
DeviceMotionEvent
在设备发生摆动、运动(手机疯狂摇摆,摇一摇场景)时产生。数组
devicemotion
是用来监听手机加速度变化的事件回调中能够提供设备的加速度信息。
表示为在设备上定义的坐标系中的笛卡尔坐标,提供了设备在坐标系中的自转速率。浏览器
对于一个竖屏摆放的设备来讲,设备三个方向轴的位置为:微信
有 4 个只读属性:属性测试Demo,摇晃小球Demo(加速度)测试
m/s²
。重力加速度(包括重心引力)m/s²
。加速度(须要设备陀螺仪支持)°/s
(degrees per seconds) 。旋转速度 DeviceOrientationEvent
加速度传感器检测到设备在方向上产生变化时触发。
监听设备方向(设备旋转和仰角变化的行为),提供设备的物理方向信息,表示为一系列本地坐标系的旋角。this
属性有三个,用于描述设备方向:属性测试,摇晃小球Demo(当前设备方向)spa
当手机禁止的时候你会发现他是不动的。拿起移动时就会发现回调开始调用。
devicemotion-demo 咱们可使用 devicemotion
直接来监听设备的运动,当他超过特定的阈值,咱们就认为在摇一摇。
接下来,咱们能够摇起来了,能够看到背景色会从绿色变为黄色,而后也有触发阈值的次数的统计。
window.addEventListener('devicemotion', (e) => { console.log(e) if(this.devicemotionReturn) return ; this.historyDevicemotion = JSON.parse(JSON.stringify(this.devicemotion)) this.devicemotion.accelerationIncludingGravity.x = e.accelerationIncludingGravity.x this.devicemotion.accelerationIncludingGravity.y = e.accelerationIncludingGravity.y this.devicemotion.accelerationIncludingGravity.z = e.accelerationIncludingGravity.z if(this.historyDevicemotion.accelerationIncludingGravity.x || this.historyDevicemotion.accelerationIncludingGravity.y || this.historyDevicemotion.accelerationIncludingGravity.z){ // 计算单一方向加速度的差值 var thresholdCount = Math.max( Math.abs(this.historyDevicemotion.accelerationIncludingGravity.x - e.accelerationIncludingGravity.x), Math.abs(this.historyDevicemotion.accelerationIncludingGravity.y - e.accelerationIncludingGravity.y), Math.abs(this.historyDevicemotion.accelerationIncludingGravity.z - e.accelerationIncludingGravity.z) ) // 阈值判断 if(thresholdCount > 1) this.devicemotion.thresholdCount_1++; if(thresholdCount > 5) this.devicemotion.thresholdCount_5++; if(thresholdCount > 10) this.devicemotion.thresholdCount_10++; if(thresholdCount > 15) this.devicemotion.thresholdCount_15++; if(thresholdCount > 20) this.devicemotion.thresholdCount_20++; if(thresholdCount > 25) this.devicemotion.thresholdCount_25++; if(thresholdCount > 50) this.devicemotion.thresholdCount_50++; if(thresholdCount > 100) this.devicemotion.thresholdCount_100++; // 颜色变化逻辑 if(thresholdCount > 20) this.devicemotion.shakeValue = Math.min(255, this.devicemotion.shakeValue + 10) } })
deviceorientation
来监听设备的方向变化,也是设置阈值,超过必定的幅度咱们就认为在摇动手机。测试方法同上我就很少介绍了。测试地址 Navigator.vibrate()
可使设备(需硬件支持,手机通常都有响铃并震动功能)产生有频率(能够传入数组)的震动。
若设备不支持震动,该方法将无效。
若某震动方式已经在进行中(当该方法调用时),则前一个震动方式中止,新的取而代之。
若由于提供无效的参数使得没法使设备震动,它将返回false,不然返回true。
若振动方案致使长时间的震动,它会被截断:最大震动时长取决于每一个浏览器的具体实现。
navigator.vibrate(duration);
window.navigator.vibrate(200);
一个200ms的震动window.navigator.vibrate(0);
中止震动,能够理解为覆盖,而后震动0mswindow.navigator.vibrate([100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100]);
有频率的震动,奇数位为震动时间,偶数位为暂停时间。我下标按1开始的啊。声音播放咱们就直接使用 audio 标签实现便可,测试地址。复杂一点能够看我以前写的基于better-scroll 实现歌词联动功能。
欢迎你们关注个人公众号。有疑问也能够加个人微信前端交流群。