shake.vue 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <template>
  2. <view class="root" :style="{backgroundImage:'url('+img+')'}">
  3. <view :class="[show ? 'up' : '','shake-up']">
  4. <image mode="aspectFit" src="https://img-cdn-qiniu.dcloud.net.cn/uniapp/shake/shakeup.png"></image>
  5. </view>
  6. <view :class="[show ? 'down' : '','shake-down']">
  7. <image mode="aspectFit" src="https://img-cdn-qiniu.dcloud.net.cn/uniapp/shake/shakedown.png"></image>
  8. </view>
  9. </view>
  10. </template>
  11. <script>
  12. export default {
  13. data() {
  14. return {
  15. img: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/shake/1.jpg',
  16. show: false,
  17. isOpened: false
  18. }
  19. },
  20. onLoad: function () {
  21. this.music = uni.createInnerAudioContext();
  22. this.music.src = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/shake/shake.wav';
  23. let index = 1,
  24. t = null;
  25. uni.onAccelerometerChange((res) => {
  26. if (Math.abs(res.x) + Math.abs(res.y) + Math.abs(res.z) > 20 && !this.show && this.isOpened) {
  27. this.music.play();
  28. setTimeout(() => {
  29. index++;
  30. if (index > 4) {
  31. index = 1
  32. }
  33. this.img = 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/shake/' + index + '.jpg';
  34. }, 2000);
  35. this.show = true;
  36. if (t) {
  37. clearTimeout(t);
  38. }
  39. t = setTimeout(() => {
  40. t = null;
  41. this.show = false;
  42. }, 600)
  43. }
  44. })
  45. },
  46. onShow() {
  47. this.isOpened = true;
  48. },
  49. onUnload() {
  50. this.show = false;
  51. this.isOpened = false;
  52. uni.stopAccelerometer();
  53. this.music.destroy();
  54. }
  55. }
  56. </script>
  57. <style>
  58. .root {
  59. height: 100%;
  60. display: flex;
  61. flex-direction: column;
  62. background-position: center center;
  63. background-repeat: no-repeat;
  64. }
  65. .shake-up,
  66. .shake-down {
  67. height: 50%;
  68. overflow: hidden;
  69. transition: all .5s ease-in-out;
  70. -webkit-transition: all .5s ease-in-out;
  71. background: #333;
  72. }
  73. .up {
  74. transform: translateY(-50%);
  75. -webkit-transform: translateY(-50%);
  76. }
  77. .down {
  78. transform: translateY(50%);
  79. -webkit-transform: translateY(50%);
  80. }
  81. image {
  82. height: 100%;
  83. width: 100%;
  84. }
  85. </style>