image.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. let incId = 1;
  2. const noop = function () { };
  3. class GImage {
  4. static GBridge = null;
  5. constructor() {
  6. this._id = incId++;
  7. this._width = 0;
  8. this._height = 0;
  9. this._src = undefined;
  10. this._onload = noop;
  11. this._onerror = noop;
  12. this.complete = false;
  13. }
  14. get width() {
  15. return this._width;
  16. }
  17. set width(v) {
  18. this._width = v;
  19. }
  20. get height() {
  21. return this._height;
  22. }
  23. set height(v) {
  24. this._height = v;
  25. }
  26. get src() {
  27. return this._src;
  28. }
  29. set src(v) {
  30. if (v.startsWith('//')) {
  31. v = 'http:' + v;
  32. }
  33. this._src = v;
  34. GImage.GBridge.perloadImage([this._src, this._id], (data) => {
  35. if (typeof data === 'string') {
  36. data = JSON.parse(data);
  37. }
  38. if (data.error) {
  39. var evt = { type: 'error', target: this };
  40. this.onerror(evt);
  41. } else {
  42. this.complete = true;
  43. this.width = typeof data.width === 'number' ? data.width : 0;
  44. this.height = typeof data.height === 'number' ? data.height : 0;
  45. var evt = { type: 'load', target: this };
  46. this.onload(evt);
  47. }
  48. });
  49. }
  50. addEventListener(name, listener) {
  51. if (name === 'load') {
  52. this.onload = listener;
  53. } else if (name === 'error') {
  54. this.onerror = listener;
  55. }
  56. }
  57. removeEventListener(name, listener) {
  58. if (name === 'load') {
  59. this.onload = noop;
  60. } else if (name === 'error') {
  61. this.onerror = noop;
  62. }
  63. }
  64. get onload() {
  65. return this._onload;
  66. }
  67. set onload(v) {
  68. this._onload = v;
  69. }
  70. get onerror() {
  71. return this._onerror;
  72. }
  73. set onerror(v) {
  74. this._onerror = v;
  75. }
  76. }
  77. export default GImage;