canvas.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. Component({
  2. data: {
  3. finalPixelRatio: 1,
  4. },
  5. properties: {
  6. style: {
  7. type: String,
  8. value: '',
  9. },
  10. width: {
  11. type: Number,
  12. value: 100,
  13. },
  14. height: {
  15. type: Number,
  16. value: 100,
  17. },
  18. onInit: {
  19. type: Function,
  20. value: function value() {},
  21. },
  22. onTouchEvent: {
  23. type: Function,
  24. value: function value() {},
  25. },
  26. onError: {
  27. type: Function,
  28. value: function value() {},
  29. },
  30. pixelRatio: {
  31. type: Number,
  32. value: 1,
  33. },
  34. },
  35. observers: {
  36. pixelRatio: function (pixelRatio) {
  37. this.setData({
  38. finalPixelRatio: pixelRatio >= 1 ? Math.ceil(pixelRatio) : 1,
  39. });
  40. },
  41. },
  42. ready: function ready() {
  43. const query = wx.createSelectorQuery().in(this);
  44. query
  45. .select('#f6-canvas')
  46. .fields({
  47. node: true,
  48. size: true,
  49. })
  50. .exec((ret) => {
  51. console.log('ret', ret);
  52. var canvas = ret[0].node;
  53. const finalPixelRatio = this.data.finalPixelRatio;
  54. canvas.width = this.data.width * finalPixelRatio;
  55. canvas.height = this.data.height * finalPixelRatio;
  56. this.rect = {
  57. width: this.data.width * finalPixelRatio,
  58. height: this.data.height * finalPixelRatio,
  59. left: canvas._left,
  60. top: canvas._top,
  61. };
  62. console.log('rect', this.rect);
  63. this.ctx = canvas.getContext('2d');
  64. this.triggerEvent('onInit', {
  65. ctx: this.ctx,
  66. rect: this.rect,
  67. canvas: canvas,
  68. renderer: 'mini-native',
  69. });
  70. });
  71. },
  72. methods: {
  73. error: function error(e) {
  74. this.data.onError(e);
  75. },
  76. ontouch: function ontouch(e) {
  77. var i = 0;
  78. for (i = 0; i < e.touches.length; i++) {
  79. modifyEvent(e.touches[i]);
  80. }
  81. for (i = 0; i < e.changedTouches.length; i++) {
  82. modifyEvent(e.changedTouches[i]);
  83. }
  84. this.triggerEvent('onTouchEvent', e);
  85. },
  86. },
  87. });
  88. function modifyEvent(touchEvent) {
  89. touchEvent.clientX = touchEvent.x;
  90. touchEvent.clientY = touchEvent.y;
  91. touchEvent.pageX = touchEvent.x;
  92. touchEvent.pageY = touchEvent.y;
  93. }