wx-canvas.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export default class WxCanvas {
  2. constructor(ctx, canvasId) {
  3. this.ctx = ctx;
  4. this.canvasId = canvasId;
  5. this.chart = null;
  6. WxCanvas.initStyle(ctx);
  7. this.initEvent();
  8. }
  9. getContext(contextType) {
  10. return contextType === '2d' ? this.ctx : null;
  11. }
  12. setChart(chart) {
  13. this.chart = chart;
  14. }
  15. attachEvent() {
  16. // noop
  17. }
  18. detachEvent() {
  19. // noop
  20. }
  21. static initStyle(ctx) {
  22. const styles = ['fillStyle', 'strokeStyle', 'globalAlpha',
  23. 'textAlign', 'textBaseAlign', 'shadow', 'lineWidth',
  24. 'lineCap', 'lineJoin', 'lineDash', 'miterLimit', 'fontSize'];
  25. styles.forEach((style) => {
  26. Object.defineProperty(ctx, style, {
  27. set: (value) => {
  28. if ((style !== 'fillStyle' && style !== 'strokeStyle')
  29. || (value !== 'none' && value !== null)
  30. ) {
  31. ctx[`set${style.charAt(0).toUpperCase()}${style.slice(1)}`](value);
  32. }
  33. },
  34. });
  35. });
  36. ctx.createRadialGradient = () => ctx.createCircularGradient(arguments);
  37. }
  38. initEvent() {
  39. this.event = {};
  40. const eventNames = [{
  41. wxName: 'touchStart',
  42. ecName: 'mousedown',
  43. }, {
  44. wxName: 'touchMove',
  45. ecName: 'mousemove',
  46. }, {
  47. wxName: 'touchEnd',
  48. ecName: 'mouseup',
  49. }, {
  50. wxName: 'touchEnd',
  51. ecName: 'click',
  52. }];
  53. eventNames.forEach((name) => {
  54. this.event[name.wxName] = (e) => {
  55. const touch = e.mp.touches[0];
  56. this.chart._zr.handler.dispatch(name.ecName, {
  57. zrX: name.wxName === 'tap' ? touch.clientX : touch.x,
  58. zrY: name.wxName === 'tap' ? touch.clientY : touch.y,
  59. });
  60. };
  61. });
  62. }
  63. }