index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * @Author: rileycai
  3. * @Date: 2022-03-14 14:21:26
  4. * @LastEditTime: 2022-03-14 15:23:04
  5. * @LastEditors: rileycai
  6. * @Description: webp-image组件对t-image包裹了一层,主要实现图片裁剪、webp压缩功能
  7. * @FilePath: /tdesign-miniprogram-starter/components/webp-image/index.js
  8. */
  9. // Replace deprecated wx.getSystemInfoSync()
  10. const systemInfo = {
  11. ...wx.getWindowInfo(),
  12. ...wx.getDeviceInfo()
  13. };
  14. Component({
  15. externalClasses: ['t-class', 't-class-load'],
  16. properties: {
  17. loadFailed: {
  18. type: String,
  19. value: 'default',
  20. },
  21. loading: {
  22. type: String,
  23. value: 'default',
  24. },
  25. src: {
  26. type: String,
  27. value: '',
  28. },
  29. mode: {
  30. type: String,
  31. value: 'aspectFill',
  32. },
  33. webp: {
  34. type: Boolean,
  35. value: true,
  36. },
  37. lazyLoad: {
  38. type: Boolean,
  39. value: false,
  40. },
  41. showMenuByLongpress: {
  42. type: Boolean,
  43. value: false,
  44. },
  45. },
  46. data: {
  47. thumbHeight: 375,
  48. thumbWidth: 375,
  49. systemInfo,
  50. },
  51. lifetimes: {
  52. ready() {
  53. const { mode } = this.properties;
  54. // 获取容器的真实宽高,设置图片的裁剪宽度
  55. this.getRect('.J-image').then((res) => {
  56. if (res) {
  57. const { width, height } = res;
  58. this.setData(
  59. mode === 'heightFix'
  60. ? {
  61. thumbHeight: this.px2rpx(height) || 375,
  62. }
  63. : {
  64. thumbWidth: this.px2rpx(width) || 375,
  65. },
  66. );
  67. }
  68. });
  69. },
  70. },
  71. methods: {
  72. px2rpx(px) {
  73. return (750 / (systemInfo.screenWidth || 375)) * px;
  74. },
  75. getRect(selector) {
  76. return new Promise((resolve) => {
  77. if (!this.selectorQuery) {
  78. this.selectorQuery = this.createSelectorQuery();
  79. }
  80. this.selectorQuery.select(selector).boundingClientRect(resolve).exec();
  81. });
  82. },
  83. onLoad(e) {
  84. this.triggerEvent('load', e.detail);
  85. },
  86. onError(e) {
  87. this.triggerEvent('error', e.detail);
  88. },
  89. },
  90. });