index.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // @ts-nocheck
  2. import {isBrowser} from '../isBrowser'
  3. class Image {
  4. currentSrc: string | null = null
  5. naturalHeight: number = 0
  6. naturalWidth: number = 0
  7. width: number = 0
  8. height: number = 0
  9. tagName: string = 'IMG'
  10. path: string = ''
  11. crossOrigin: string = ''
  12. referrerPolicy: string = ''
  13. onload: () => void
  14. onerror: () => void
  15. complete: boolean = false
  16. constructor() {}
  17. set src(src: string) {
  18. src = src.replace(/^@\//,'/')
  19. this.currentSrc = src
  20. uni.getImageInfo({
  21. src,
  22. success: (res) => {
  23. const localReg = /^\.|^\/(?=[^\/])/;
  24. // #ifdef MP-WEIXIN || MP-BAIDU || MP-QQ || MP-TOUTIAO
  25. res.path = localReg.test(src) ? `/${res.path}` : res.path;
  26. // #endif
  27. this.complete = true
  28. this.path = res.path
  29. this.naturalWidth = this.width = res.width
  30. this.naturalHeight = this.height = res.height
  31. this.onload()
  32. },
  33. fail: () => {
  34. this.onerror()
  35. }
  36. })
  37. }
  38. get src() {
  39. return this.currentSrc
  40. }
  41. }
  42. interface UniImage extends WechatMiniprogram.Image {
  43. complete?: boolean
  44. naturalHeight?: number
  45. naturalWidth?: number
  46. }
  47. /** 创建用于 canvas 的 img */
  48. export function createImage(canvas?: any): HTMLImageElement | UniImage {
  49. if(canvas && canvas.createImage) {
  50. return (canvas as WechatMiniprogram.Canvas).createImage()
  51. } else if(canvas && !('toBlob' in canvas)){
  52. return new Image()
  53. } else if(isBrowser) {
  54. return new window.Image()
  55. }
  56. return new Image()
  57. }