wx-canvas.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. export default class WxCanvas {
  2. constructor(ctx, canvasId) {
  3. this.ctx = ctx;
  4. this.canvasId = canvasId;
  5. this.chart = null;
  6. // this._initCanvas(zrender, ctx);
  7. this._initStyle(ctx);
  8. this._initEvent();
  9. }
  10. getContext(contextType) {
  11. if (contextType === '2d') {
  12. return this.ctx;
  13. }
  14. }
  15. // canvasToTempFilePath(opt) {
  16. // if (!opt.canvasId) {
  17. // opt.canvasId = this.canvasId;
  18. // }
  19. // return wx.canvasToTempFilePath(opt, this);
  20. // }
  21. setChart(chart) {
  22. this.chart = chart;
  23. }
  24. attachEvent() {
  25. // noop
  26. }
  27. detachEvent() {
  28. // noop
  29. }
  30. _initCanvas(zrender, ctx) {
  31. zrender.util.getContext = function () {
  32. return ctx;
  33. };
  34. zrender.util.$override('measureText', function (text, font) {
  35. ctx.font = font || '12px sans-serif';
  36. return ctx.measureText(text);
  37. });
  38. }
  39. _initStyle(ctx) {
  40. var styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
  41. 'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
  42. 'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'
  43. ];
  44. styles.forEach(style => {
  45. Object.defineProperty(ctx, style, {
  46. set: value => {
  47. if (style !== 'fillStyle' && style !== 'strokeStyle' ||
  48. value !== 'none' && value !== null
  49. ) {
  50. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  51. }
  52. }
  53. });
  54. });
  55. ctx.createRadialGradient = () => {
  56. return ctx.createCircularGradient(arguments);
  57. };
  58. }
  59. _initEvent() {
  60. this.event = {};
  61. const eventNames = [{
  62. wxName: 'touchStart',
  63. ecName: 'mousedown'
  64. }, {
  65. wxName: 'touchMove',
  66. ecName: 'mousemove'
  67. }, {
  68. wxName: 'touchEnd',
  69. ecName: 'mouseup'
  70. }, {
  71. wxName: 'touchEnd',
  72. ecName: 'click'
  73. }];
  74. eventNames.forEach(name => {
  75. this.event[name.wxName] = e => {
  76. const touch = e.touches[0];
  77. this.chart.getZr().handler.dispatch(name.ecName, {
  78. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  79. zrY: name.wxName === 'tap' ? touch.clientY : touch.y
  80. });
  81. };
  82. });
  83. }
  84. }