canvas-element.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. "use strict";
  2. exports.__esModule = true;
  3. exports["default"] = void 0;
  4. var _emit = _interopRequireDefault(require("../event/emit"));
  5. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  6. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  7. var CanvasElement = /*#__PURE__*/function (_EventEmit) {
  8. _inheritsLoose(CanvasElement, _EventEmit);
  9. function CanvasElement(ctx) {
  10. var _this;
  11. _this = _EventEmit.call(this) || this;
  12. _this.context = ctx; // canvas实际的宽高 (width/height) * pixelRatio
  13. _this.width = 0;
  14. _this.height = 0;
  15. _this.style = {};
  16. _this.currentStyle = {};
  17. _this.attrs = {}; // 用来标识是CanvasElement实例
  18. _this.isCanvasElement = true;
  19. return _this;
  20. }
  21. var _proto = CanvasElement.prototype;
  22. _proto.getContext = function getContext()
  23. /* type */
  24. {
  25. return this.context;
  26. };
  27. _proto.getBoundingClientRect = function getBoundingClientRect() {
  28. var width = this.width;
  29. var height = this.height; // 默认都处理成可视窗口的顶部位置
  30. return {
  31. top: 0,
  32. right: width,
  33. bottom: height,
  34. left: 0
  35. };
  36. };
  37. _proto.setAttribute = function setAttribute(key, value) {
  38. this.attrs[key] = value;
  39. };
  40. _proto.addEventListener = function addEventListener(type, listener) {
  41. this.on(type, listener);
  42. };
  43. _proto.removeEventListener = function removeEventListener(type, listener) {
  44. this.off(type, listener);
  45. };
  46. _proto.dispatchEvent = function dispatchEvent(type, e) {
  47. this.emit(type, e);
  48. };
  49. return CanvasElement;
  50. }(_emit["default"]);
  51. function supportEventListener(canvas) {
  52. if (!canvas) {
  53. return false;
  54. } // 非 HTMLCanvasElement
  55. if (canvas.nodeType !== 1 || !canvas.nodeName || canvas.nodeName.toLowerCase() !== 'canvas') {
  56. return false;
  57. } // 微信小程序canvas.getContext('2d')时也是CanvasRenderingContext2D
  58. // 也会有ctx.canvas, 而且nodeType也是1,所以还要在看下是否支持addEventListener
  59. var support = false;
  60. try {
  61. canvas.addEventListener('eventTest', function () {
  62. support = true;
  63. });
  64. canvas.dispatchEvent(new Event('eventTest'));
  65. } catch (error) {
  66. support = false;
  67. }
  68. return support;
  69. }
  70. var _default = {
  71. create: function create(ctx) {
  72. if (!ctx) {
  73. return null;
  74. }
  75. if (supportEventListener(ctx.canvas)) {
  76. return ctx.canvas;
  77. }
  78. return new CanvasElement(ctx);
  79. }
  80. };
  81. exports["default"] = _default;