wx-canvas.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. attachEvent() {
  31. // noop
  32. }
  33. detachEvent() {
  34. // noop
  35. }
  36. _initCanvas(zrender, ctx) {
  37. zrender.util.getContext = function () {
  38. return ctx;
  39. };
  40. zrender.util.$override('measureText', function (text, font) {
  41. ctx.font = font || '12px sans-serif';
  42. return ctx.measureText(text);
  43. });
  44. }
  45. _initStyle(ctx) {
  46. ctx.createRadialGradient = () => {
  47. return ctx.createCircularGradient(arguments);
  48. };
  49. }
  50. _initEvent() {
  51. this.event = {};
  52. const eventNames = [{
  53. wxName: 'touchStart',
  54. ecName: 'mousedown'
  55. }, {
  56. wxName: 'touchMove',
  57. ecName: 'mousemove'
  58. }, {
  59. wxName: 'touchEnd',
  60. ecName: 'mouseup'
  61. }, {
  62. wxName: 'touchEnd',
  63. ecName: 'click'
  64. }];
  65. eventNames.forEach(name => {
  66. this.event[name.wxName] = e => {
  67. const touch = e.touches[0];
  68. this.chart.getZr().handler.dispatch(name.ecName, {
  69. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  70. zrY: name.wxName === 'tap' ? touch.clientY : touch.y
  71. });
  72. };
  73. });
  74. }
  75. set width(w) {
  76. if (this.canvasNode) this.canvasNode.width = w
  77. }
  78. set height(h) {
  79. if (this.canvasNode) this.canvasNode.height = h
  80. }
  81. get width() {
  82. if (this.canvasNode)
  83. return this.canvasNode.width
  84. return 0
  85. }
  86. get height() {
  87. if (this.canvasNode)
  88. return this.canvasNode.height
  89. return 0
  90. }
  91. }