ImageFlexContain.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <template>
  2. <div class="image-flex-contain">
  3. <div class="image-flex-image" :style="styles">
  4. <img
  5. :src="image.url"
  6. :alt="image.title"
  7. @load="resizeImage(initRotate)"
  8. />
  9. </div>
  10. </div>
  11. </template>
  12. <script>
  13. export default {
  14. name: "image-flex-contain",
  15. props: {
  16. image: {
  17. type: Object,
  18. default() {
  19. return {};
  20. }
  21. },
  22. initRotate: {
  23. type: Number,
  24. default: 0
  25. }
  26. },
  27. data() {
  28. return {
  29. styles: { width: "", height: "", top: "", left: "", transform: "" },
  30. deg: this.initRotate
  31. };
  32. },
  33. mounted() {
  34. this.registWinResize();
  35. },
  36. beforeDestroy() {
  37. window.removeEventListener("resize", () => {
  38. this.resizeImage(this.deg);
  39. });
  40. },
  41. methods: {
  42. registWinResize() {
  43. window.addEventListener("resize", () => {
  44. this.resizeImage(this.deg);
  45. });
  46. },
  47. resizeImage(deg = 0) {
  48. this.deg = deg;
  49. const box = this.$el;
  50. const imgDom = box.firstChild.firstChild;
  51. const { naturalWidth, naturalHeight } = imgDom;
  52. const imageSize = this.getImageSizePos({
  53. win: {
  54. width: box.clientWidth,
  55. height: box.clientHeight
  56. },
  57. img: {
  58. width: naturalWidth,
  59. height: naturalHeight
  60. },
  61. rotate: deg
  62. });
  63. this.styles = Object.assign(this.styles, {
  64. width: imageSize.width + "px",
  65. height: imageSize.height + "px",
  66. top: imageSize.top + "px",
  67. left: imageSize.left + "px",
  68. transform: `rotate(${deg}deg)`
  69. });
  70. },
  71. getImageSizePos({ win, img, rotate }) {
  72. const imageSize = {
  73. width: 0,
  74. height: 0,
  75. top: 0,
  76. left: 0
  77. };
  78. const isHorizontal = !!(rotate % 180);
  79. const rateWin = isHorizontal
  80. ? win.height / win.width
  81. : win.width / win.height;
  82. const hwin = isHorizontal
  83. ? {
  84. width: win.height,
  85. height: win.width
  86. }
  87. : win;
  88. const rateImg = img.width / img.height;
  89. if (rateImg <= rateWin) {
  90. imageSize.height = Math.min(hwin.height, img.height);
  91. imageSize.width = Math.floor(
  92. (imageSize.height * img.width) / img.height
  93. );
  94. } else {
  95. imageSize.width = Math.min(hwin.width, img.width);
  96. imageSize.height = Math.floor(
  97. (imageSize.width * img.height) / img.width
  98. );
  99. }
  100. imageSize.left = (win.width - imageSize.width) / 2;
  101. imageSize.top = (win.height - imageSize.height) / 2;
  102. return imageSize;
  103. }
  104. }
  105. };
  106. </script>