ScaleBox.vue 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <div class="ScaleBox" ref="ScaleBox" :style="{
  3. width: width + 'px',
  4. height: height + 'px',
  5. }">
  6. <slot :scale="scale"></slot>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name: "ScaleBox",
  12. props: {},
  13. data() {
  14. return {
  15. scale: 0,
  16. width: 1920,
  17. height: 1080,
  18. };
  19. },
  20. mounted() {
  21. this.setScale();
  22. window.addEventListener("resize", this.debounce(this.setScale));
  23. },
  24. methods: {
  25. getScale() {
  26. // 固定好16:9的宽高比,计算出最合适的缩放比
  27. const {
  28. width,
  29. height
  30. } = this;
  31. const wh = window.innerHeight / height;
  32. const ww = window.innerWidth / width;
  33. // console.log(ww < wh ? ww : wh);
  34. return ww < wh ? ww : wh;
  35. },
  36. setScale() {
  37. // 获取到缩放比例,设置它
  38. this.scale = this.getScale();
  39. if (this.$refs.ScaleBox) {
  40. this.$refs.ScaleBox.style.setProperty("--scale", this.scale);
  41. }
  42. },
  43. debounce(fn, delay) {
  44. const delays = delay || 500;
  45. let timer;
  46. return function() {
  47. const th = this;
  48. const args = arguments;
  49. if (timer) {
  50. clearTimeout(timer);
  51. }
  52. timer = setTimeout(function() {
  53. timer = null;
  54. fn.apply(th, args);
  55. }, delays);
  56. };
  57. },
  58. },
  59. };
  60. </script>
  61. <style>
  62. #ScaleBox {
  63. --scale: 1;
  64. }
  65. .ScaleBox {
  66. position: absolute;
  67. transform: scale(var(--scale)) translate(-50%, -50%);
  68. display: flex;
  69. flex-direction: column;
  70. transform-origin: 0 0;
  71. left: 50%;
  72. top: 50%;
  73. transition: 0.3s;
  74. z-index: 999;
  75. /* // background: rgba(255, 0, 0, 0.3); */
  76. }
  77. </style>