canvas-element.js 1.7 KB

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