f2-canvas.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // f2-canvas.js
  2. import Renderer from './lib/renderer';
  3. import F2 from './lib/f2.js';
  4. // 适配小程序的事件机制
  5. F2.Util.addEventListener = function (source, type, listener) {
  6. source.addListener(type, listener);
  7. };
  8. F2.Util.removeEventListener = function (source, type, listener) {
  9. source.removeListener(type, listener);
  10. };
  11. F2.Util.createEvent = function (event, chart) {
  12. const type = event.type;
  13. let x = 0;
  14. let y = 0;
  15. const touches = event.touches;
  16. if (touches && touches.length > 0) {
  17. x = touches[0].x;
  18. y = touches[0].y;
  19. }
  20. return {
  21. type,
  22. chart,
  23. x,
  24. y
  25. };
  26. };
  27. Component({
  28. /**
  29. * 组件的属性列表
  30. */
  31. properties: {
  32. canvasId: {
  33. type: String,
  34. value: 'f2-canvas'
  35. },
  36. opts: {
  37. type: Object
  38. }
  39. },
  40. /**
  41. * 组件的初始数据
  42. */
  43. data: {
  44. },
  45. ready: function () {
  46. if (!this.data.opts) {
  47. console.warn('组件需绑定 opts 变量,例:<ff-canvas id="mychart-dom-bar" '
  48. + 'canvas-id="mychart-bar" opts="{{ opts }}"></ff-canvas>');
  49. return;
  50. }
  51. if (!this.data.opts.lazyLoad) {
  52. this.init();
  53. }
  54. },
  55. /**
  56. * 组件的方法列表
  57. */
  58. methods: {
  59. init: function(callback) {
  60. const version = wx.version.version.split('.').map(n => parseInt(n, 10));
  61. const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9)
  62. || (version[0] === 1 && version[1] === 9 && version[2] >= 91);
  63. if (!isValid) {
  64. console.error('微信基础库版本过低,需大于等于 1.9.91。');
  65. return;
  66. }
  67. const ctx = wx.createCanvasContext(this.data.canvasId, this); // 获取小程序上下文
  68. const canvas = new Renderer(ctx);
  69. this.canvas = canvas;
  70. const query = wx.createSelectorQuery().in(this);
  71. query.select('.f2-canvas').boundingClientRect(res => {
  72. if (typeof callback === 'function') {
  73. this.chart = callback(canvas, res.width, res.height);
  74. } else if (this.data.opts && this.data.opts.onInit) {
  75. this.chart = this.data.opts.onInit(canvas, res.width, res.height);
  76. }
  77. }).exec();
  78. },
  79. touchStart(e) {
  80. if (this.canvas) {
  81. this.canvas.emitEvent('touchstart', [e]);
  82. }
  83. },
  84. touchMove(e) {
  85. if (this.canvas) {
  86. this.canvas.emitEvent('touchmove', [e]);
  87. }
  88. },
  89. touchEnd(e) {
  90. if (this.canvas) {
  91. this.canvas.emitEvent('touchend', [e]);
  92. }
  93. },
  94. press(e) {
  95. if (this.canvas) {
  96. this.canvas.emitEvent('press', [e]);
  97. }
  98. }
  99. }
  100. })