image.js 2.0 KB

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