wx-canvas.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. export default class WxCanvas {
  2. constructor(ctx, canvasId, isNew, canvasNode) {
  3. this.ctx = ctx;
  4. this.canvasId = canvasId;
  5. this.chart = null;
  6. this.isNew = isNew
  7. if (isNew) {
  8. this.canvasNode = canvasNode;
  9. }
  10. else {
  11. this._initStyle(ctx);
  12. }
  13. // this._initCanvas(zrender, ctx);
  14. this._initEvent();
  15. }
  16. getContext(contextType) {
  17. if (contextType === '2d') {
  18. return this.ctx;
  19. }
  20. }
  21. // canvasToTempFilePath(opt) {
  22. // if (!opt.canvasId) {
  23. // opt.canvasId = this.canvasId;
  24. // }
  25. // return wx.canvasToTempFilePath(opt, this);
  26. // }
  27. setChart(chart) {
  28. this.chart = chart;
  29. }
  30. addEventListener() {
  31. // noop
  32. }
  33. attachEvent() {
  34. // noop
  35. }
  36. detachEvent() {
  37. // noop
  38. }
  39. _initCanvas(zrender, ctx) {
  40. zrender.util.getContext = function () {
  41. return ctx;
  42. };
  43. zrender.util.$override('measureText', function (text, font) {
  44. ctx.font = font || '12px sans-serif';
  45. return ctx.measureText(text);
  46. });
  47. }
  48. _initStyle(ctx) {
  49. ctx.createRadialGradient = () => {
  50. return ctx.createCircularGradient(arguments);
  51. };
  52. }
  53. _initEvent() {
  54. this.event = {};
  55. const eventNames = [{
  56. wxName: 'touchStart',
  57. ecName: 'mousedown'
  58. }, {
  59. wxName: 'touchMove',
  60. ecName: 'mousemove'
  61. }, {
  62. wxName: 'touchEnd',
  63. ecName: 'mouseup'
  64. }, {
  65. wxName: 'touchEnd',
  66. ecName: 'click'
  67. }];
  68. eventNames.forEach(name => {
  69. this.event[name.wxName] = e => {
  70. const touch = e.touches[0];
  71. this.chart.getZr().handler.dispatch(name.ecName, {
  72. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  73. zrY: name.wxName === 'tap' ? touch.clientY : touch.y,
  74. preventDefault: () => {},
  75. stopImmediatePropagation: () => {},
  76. stopPropagation: () => {}
  77. });
  78. };
  79. });
  80. }
  81. set width(w) {
  82. if (this.canvasNode) this.canvasNode.width = w
  83. }
  84. set height(h) {
  85. if (this.canvasNode) this.canvasNode.height = h
  86. }
  87. get width() {
  88. if (this.canvasNode)
  89. return this.canvasNode.width
  90. return 0
  91. }
  92. get height() {
  93. if (this.canvasNode)
  94. return this.canvasNode.height
  95. return 0
  96. }
  97. }