index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. console.log('src', src)
  19. if(!src) {
  20. return this.onerror()
  21. }
  22. src = src.replace(/^@\//,'/')
  23. this.currentSrc = src
  24. uni.getImageInfo({
  25. src,
  26. success: (res) => {
  27. const localReg = /^\.|^\/(?=[^\/])/;
  28. // #ifdef MP-WEIXIN || MP-BAIDU || MP-QQ || MP-TOUTIAO
  29. res.path = localReg.test(src) ? `/${res.path}` : res.path;
  30. // #endif
  31. this.complete = true
  32. this.path = res.path
  33. this.naturalWidth = this.width = res.width
  34. this.naturalHeight = this.height = res.height
  35. this.onload()
  36. },
  37. fail: () => {
  38. this.onerror()
  39. }
  40. })
  41. }
  42. get src() {
  43. return this.currentSrc
  44. }
  45. }
  46. interface UniImage extends WechatMiniprogram.Image {
  47. complete?: boolean
  48. naturalHeight?: number
  49. naturalWidth?: number
  50. }
  51. /** 创建用于 canvas 的 img */
  52. export function createImage(canvas?: any): HTMLImageElement | UniImage {
  53. if(canvas && canvas.createImage) {
  54. return (canvas as WechatMiniprogram.Canvas).createImage()
  55. } else if(this.tagName == 'canvas' && !('toBlob' in this) || canvas && !('toBlob' in canvas)){
  56. return new Image()
  57. } else if(isBrowser) {
  58. return new window.Image()
  59. }
  60. return new Image()
  61. }