ec-canvas.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import WxCanvas from './wx-canvas';
  2. import * as echarts from './echarts';
  3. let ctx;
  4. Component({
  5. properties: {
  6. canvasId: {
  7. type: String,
  8. value: 'ec-canvas'
  9. },
  10. ec: {
  11. type: Object
  12. }
  13. },
  14. data: {
  15. },
  16. ready: function () {
  17. if (!this.data.ec) {
  18. console.warn('组件需绑定 ec 变量,例:<ec-canvas id="mychart-dom-bar" '
  19. + 'canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas>');
  20. return;
  21. }
  22. if (!this.data.ec.lazyLoad) {
  23. this.init();
  24. }
  25. },
  26. methods: {
  27. init: function (callback) {
  28. const version = wx.version.version.split('.').map(n => parseInt(n, 10));
  29. const isValid = version[0] > 1 || (version[0] === 1 && version[1] > 9)
  30. || (version[0] === 1 && version[1] === 9 && version[2] >= 91);
  31. if (!isValid) {
  32. console.error('微信基础库版本过低,需大于等于 1.9.91。'
  33. + '参见:https://github.com/ecomfe/echarts-for-weixin'
  34. + '#%E5%BE%AE%E4%BF%A1%E7%89%88%E6%9C%AC%E8%A6%81%E6%B1%82');
  35. return;
  36. }
  37. ctx = wx.createCanvasContext(this.data.canvasId, this);
  38. const canvas = new WxCanvas(ctx, this.data.canvasId);
  39. echarts.setCanvasCreator(() => {
  40. return canvas;
  41. });
  42. var query = wx.createSelectorQuery().in(this);
  43. query.select('.ec-canvas').boundingClientRect(res => {
  44. if (typeof callback === 'function') {
  45. this.chart = callback(canvas, res.width, res.height);
  46. }
  47. else if (this.data.ec && this.data.ec.onInit) {
  48. this.chart = this.data.ec.onInit(canvas, res.width, res.height);
  49. }
  50. }).exec();
  51. },
  52. canvasToTempFilePath(opt) {
  53. if (!opt.canvasId) {
  54. opt.canvasId = this.data.canvasId;
  55. }
  56. ctx.draw(true, () => {
  57. wx.canvasToTempFilePath(opt, this);
  58. });
  59. },
  60. touchStart(e) {
  61. if (this.chart && e.touches.length > 0) {
  62. var touch = e.touches[0];
  63. this.chart._zr.handler.dispatch('mousedown', {
  64. zrX: touch.x,
  65. zrY: touch.y
  66. });
  67. this.chart._zr.handler.dispatch('mousemove', {
  68. zrX: touch.x,
  69. zrY: touch.y
  70. });
  71. }
  72. },
  73. touchMove(e) {
  74. if (this.chart && e.touches.length > 0) {
  75. var touch = e.touches[0];
  76. this.chart._zr.handler.dispatch('mousemove', {
  77. zrX: touch.x,
  78. zrY: touch.y
  79. });
  80. }
  81. },
  82. touchEnd(e) {
  83. if (this.chart) {
  84. const touch = e.changedTouches ? e.changedTouches[0] : {};
  85. this.chart._zr.handler.dispatch('mouseup', {
  86. zrX: touch.x,
  87. zrY: touch.y
  88. });
  89. this.chart._zr.handler.dispatch('click', {
  90. zrX: touch.x,
  91. zrY: touch.y
  92. });
  93. }
  94. }
  95. }
  96. });