index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { Canvas } from '@antv/f2';
  2. function wrapEvent(e) {
  3. if (!e) return;
  4. if (!e.preventDefault) {
  5. e.preventDefault = function () {};
  6. }
  7. return e;
  8. }
  9. Component({
  10. /**
  11. * 组件的属性列表
  12. */
  13. properties: {
  14. onRender: {
  15. type: null,
  16. value: function value() {}
  17. }
  18. },
  19. /**
  20. * 组件的初始数据
  21. */
  22. data: {},
  23. ready: function ready() {
  24. var _this = this;
  25. var query = wx.createSelectorQuery().in(this);
  26. query.select('.f2-canvas').fields({
  27. node: true,
  28. size: true
  29. }).exec(function (res) {
  30. var _res$ = res[0],
  31. node = _res$.node,
  32. width = _res$.width,
  33. height = _res$.height;
  34. var context = node.getContext('2d');
  35. var pixelRatio = wx.getSystemInfoSync().pixelRatio;
  36. // 高清设置
  37. node.width = width * pixelRatio;
  38. node.height = height * pixelRatio;
  39. var children = _this.data.onRender(_this.data);
  40. var canvas = new Canvas({
  41. pixelRatio: pixelRatio,
  42. width: width,
  43. height: height,
  44. context: context,
  45. children: children
  46. });
  47. canvas.render();
  48. _this.canvas = canvas;
  49. _this.canvasEl = canvas.canvas.get('el');
  50. });
  51. },
  52. observers: {
  53. // 处理 update
  54. '**': function _() {
  55. var canvas = this.canvas,
  56. data = this.data;
  57. if (!canvas) return;
  58. var children = data.onRender(data);
  59. canvas.update({
  60. children: children
  61. });
  62. }
  63. },
  64. lifetimes: {
  65. detached: function detached() {
  66. var canvas = this.canvas;
  67. if (!canvas) return;
  68. canvas.destroy();
  69. }
  70. },
  71. /**
  72. * 组件的方法列表
  73. */
  74. methods: {
  75. click: function click(e) {
  76. var canvasEl = this.canvasEl;
  77. if (!canvasEl) {
  78. return;
  79. }
  80. var event = wrapEvent(e);
  81. // 包装成 touch 对象
  82. event.touches = [e.detail];
  83. canvasEl.dispatchEvent('click', event);
  84. },
  85. touchStart: function touchStart(e) {
  86. var canvasEl = this.canvasEl;
  87. if (!canvasEl) {
  88. return;
  89. }
  90. canvasEl.dispatchEvent('touchstart', wrapEvent(e));
  91. },
  92. touchMove: function touchMove(e) {
  93. var canvasEl = this.canvasEl;
  94. if (!canvasEl) {
  95. return;
  96. }
  97. canvasEl.dispatchEvent('touchmove', wrapEvent(e));
  98. },
  99. touchEnd: function touchEnd(e) {
  100. var canvasEl = this.canvasEl;
  101. if (!canvasEl) {
  102. return;
  103. }
  104. canvasEl.dispatchEvent('touchend', wrapEvent(e));
  105. }
  106. }
  107. });