on-accelerometer-change.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. Page({
  2. onShareAppMessage() {
  3. return {
  4. title: '监听重力感应数据',
  5. path: 'page/API/pages/on-accelerometer-change/on-accelerometer-change'
  6. }
  7. },
  8. data: {
  9. x: 0,
  10. y: 0,
  11. z: 0,
  12. enabled: true
  13. },
  14. onReady() {
  15. this.drawBigBall()
  16. const that = this
  17. this.position = {
  18. x: 151,
  19. y: 151,
  20. vx: 0,
  21. vy: 0,
  22. ax: 0,
  23. ay: 0
  24. }
  25. wx.onAccelerometerChange(function (res) {
  26. that.setData({
  27. x: res.x.toFixed(2),
  28. y: res.y.toFixed(2),
  29. z: res.z.toFixed(2)
  30. })
  31. that.position.ax = Math.sin(res.x * Math.PI / 2)
  32. that.position.ay = -Math.sin(res.y * Math.PI / 2)
  33. // that.drawSmallBall()
  34. })
  35. this.interval = setInterval(function () {
  36. that.drawSmallBall()
  37. }, 17)
  38. },
  39. drawBigBall() {
  40. const context = wx.createContext()
  41. context.beginPath(0)
  42. context.arc(151, 151, 140, 0, Math.PI * 2)
  43. context.setFillStyle('#ffffff')
  44. context.setStrokeStyle('#aaaaaa')
  45. context.fill()
  46. // context.stroke()
  47. wx.drawCanvas({
  48. canvasId: 'big-ball',
  49. actions: context.getActions()
  50. })
  51. },
  52. drawSmallBall() {
  53. const p = this.position
  54. let strokeStyle = 'rgba(1,1,1,0)'
  55. p.x += p.vx
  56. p.y += p.vy
  57. p.vx += p.ax
  58. p.vy += p.ay
  59. // eslint-disable-next-line
  60. if (Math.sqrt(Math.pow(Math.abs(p.x) - 151, 2) + Math.pow(Math.abs(p.y) - 151, 2)) >= 115) {
  61. if (p.x > 151 && p.vx > 0) {
  62. p.vx = 0
  63. }
  64. if (p.x < 151 && p.vx < 0) {
  65. p.vx = 0
  66. }
  67. if (p.y > 151 && p.vy > 0) {
  68. p.vy = 0
  69. }
  70. if (p.y < 151 && p.vy < 0) {
  71. p.vy = 0
  72. }
  73. strokeStyle = '#ff0000'
  74. }
  75. const context = wx.createContext()
  76. context.beginPath(0)
  77. context.arc(p.x, p.y, 15, 0, Math.PI * 2)
  78. context.setFillStyle('#1aad19')
  79. context.setStrokeStyle(strokeStyle)
  80. context.fill()
  81. // context.stroke()
  82. wx.drawCanvas({
  83. canvasId: 'small-ball',
  84. actions: context.getActions()
  85. })
  86. },
  87. startAccelerometer() {
  88. if (this.data.enabled) {
  89. return
  90. }
  91. const that = this
  92. wx.startAccelerometer({
  93. success() {
  94. that.setData({
  95. enabled: true
  96. })
  97. }
  98. })
  99. },
  100. stopAccelerometer() {
  101. if (!this.data.enabled) {
  102. return
  103. }
  104. const that = this
  105. wx.stopAccelerometer({
  106. success() {
  107. that.setData({
  108. enabled: false
  109. })
  110. }
  111. })
  112. },
  113. onUnload() {
  114. clearInterval(this.interval)
  115. }
  116. })