pic.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const pic = {
  2. //预览图片
  3. preview: function(imgs, img, key) {
  4. if (imgs && imgs.length > 0) {
  5. if (key) {
  6. var temp = [];
  7. var i;
  8. for (i in imgs) {
  9. temp.push(imgs[i][key]);
  10. }
  11. imgs = temp;
  12. }
  13. // 检测图片是否原图
  14. img = this.source(img);
  15. if (imgs.length > 0) {
  16. for (i in imgs) {
  17. imgs[i] = this.source(imgs[i]);
  18. }
  19. }
  20. uni.previewImage({
  21. current: img,
  22. urls: imgs,
  23. indicator: 'default',
  24. loop: true,
  25. zIndex:999999,
  26. /*
  27. longPressActions : {
  28. itemList: ['发送给朋友', '保存图片', '收藏'],
  29. success: function(data) {
  30. console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
  31. },
  32. fail: function(err) {
  33. console.log(err.errMsg);
  34. }
  35. }
  36. */
  37. });
  38. }
  39. },
  40. //获取原图
  41. source: function(img) {
  42. if (img.indexOf('?') != -1) {
  43. var t = img.split('?');
  44. img = t[0];
  45. } else if (img.indexOf('_t') != -1) {
  46. var t = img.split('.');
  47. var ext = t[1];
  48. t = img.split('_t');
  49. img = t[0] + '.' + ext;
  50. }
  51. return img;
  52. },
  53. //计算图片宽高比
  54. getWh: function(imgWidth, imgHeight, containerWidth, containerHeight) {
  55. let [
  56. // 用于设定图片的宽和高
  57. tempWidth,
  58. tempHeight,
  59. ] = [
  60. undefined,
  61. undefined
  62. ]
  63. try {
  64. imgWidth = parseFloat(imgWidth)
  65. imgHeight = parseFloat(imgHeight)
  66. containerWidth = parseFloat(containerWidth)
  67. containerHeight = parseFloat(containerHeight)
  68. } catch (error) {
  69. throw new Error('抱歉,我只接收数值类型或者可以转成数值类型的参数')
  70. }
  71. if (imgWidth > 0 && imgHeight > 0) {
  72. //原图片宽高比例 大于 指定的宽高比例,这就说明了原图片的宽度必然 > 高度
  73. if (imgWidth / imgHeight >= containerWidth / containerHeight) {
  74. if (imgWidth > containerWidth) {
  75. // alert('aaaaaaaa')
  76. tempWidth = containerWidth
  77. // 按原图片的比例进行缩放
  78. tempHeight = (imgHeight * containerWidth) / imgWidth
  79. } else {
  80. // 按照图片的大小进行缩放
  81. tempWidth = imgWidth
  82. tempHeight = imgHeight
  83. }
  84. } else { // 原图片的高度必然 > 宽度
  85. if (imgHeight > containerHeight) {
  86. tempHeight = containerHeight
  87. // 按原图片的比例进行缩放
  88. tempWidth = (imgWidth * containerHeight) / imgHeight
  89. } else {
  90. // 按原图片的大小进行缩放
  91. tempWidth = imgWidth
  92. tempHeight = imgHeight
  93. }
  94. }
  95. }
  96. return [tempWidth, tempHeight]
  97. },
  98. }
  99. export default pic;