canvas.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. Page({
  2. onShareAppMessage() {
  3. return {
  4. title: 'canvas',
  5. path: 'page/component/pages/canvas/canvas'
  6. }
  7. },
  8. onReady() {
  9. this.position = {
  10. x: 150,
  11. y: 150,
  12. vx: 2,
  13. vy: 2
  14. }
  15. this.drawBall()
  16. this.interval = setInterval(this.drawBall, 17)
  17. },
  18. drawBall() {
  19. const p = this.position
  20. p.x += p.vx
  21. p.y += p.vy
  22. if (p.x >= 300) {
  23. p.vx = -2
  24. }
  25. if (p.x <= 7) {
  26. p.vx = 2
  27. }
  28. if (p.y >= 300) {
  29. p.vy = -2
  30. }
  31. if (p.y <= 7) {
  32. p.vy = 2
  33. }
  34. const context = wx.createCanvasContext('canvas')
  35. function ball(x, y) {
  36. context.beginPath(0)
  37. context.arc(x, y, 5, 0, Math.PI * 2)
  38. context.setFillStyle('#1aad19')
  39. context.setStrokeStyle('rgba(1,1,1,0)')
  40. context.fill()
  41. context.stroke()
  42. }
  43. ball(p.x, 150)
  44. ball(150, p.y)
  45. ball(300 - p.x, 150)
  46. ball(150, 300 - p.y)
  47. ball(p.x, p.y)
  48. ball(300 - p.x, 300 - p.y)
  49. ball(p.x, 300 - p.y)
  50. ball(300 - p.x, p.y)
  51. context.draw()
  52. },
  53. onUnload() {
  54. clearInterval(this.interval)
  55. }
  56. })