index.ts 1.7 KB

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