wx-canvas.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. styles.forEach(style => {
  44. Object.defineProperty(ctx, style, {
  45. set: value => {
  46. if (style !== 'fillStyle' && style !== 'strokeStyle'
  47. || value !== 'none' && value !== null
  48. ) {
  49. ctx['set' + style.charAt(0).toUpperCase() + style.slice(1)](value);
  50. }
  51. }
  52. });
  53. });
  54. ctx.createRadialGradient = () => {
  55. return ctx.createCircularGradient(arguments);
  56. };
  57. }
  58. _initEvent() {
  59. this.event = {};
  60. const eventNames = [{
  61. wxName: 'touchStart',
  62. ecName: 'mousedown'
  63. }, {
  64. wxName: 'touchMove',
  65. ecName: 'mousemove'
  66. }, {
  67. wxName: 'touchEnd',
  68. ecName: 'mouseup'
  69. }, {
  70. wxName: 'touchEnd',
  71. ecName: 'click'
  72. }];
  73. eventNames.forEach(name => {
  74. this.event[name.wxName] = e => {
  75. const touch = e.touches[0];
  76. this.chart.getZr().handler.dispatch(name.ecName, {
  77. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  78. zrY: name.wxName === 'tap' ? touch.clientY : touch.y
  79. });
  80. };
  81. });
  82. }
  83. }