ScreenScale.vue 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <template>
  2. <div class="container">
  3. <div ref="scaleContainer" class="scale-content">
  4. <slot />
  5. </div>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. name: 'ScreenScale',
  11. mounted() {
  12. this.calculateRatio();
  13. window.addEventListener('resize', this.calculateRatio);
  14. },
  15. beforeDestroy() {
  16. window.removeEventListener('resize', this.calculateRatio);
  17. },
  18. methods: {
  19. calculateRatio() {
  20. const baseWidth = 1920;
  21. const baseHeight = 1080;
  22. const el = this.$refs.scaleContainer;
  23. // 基于父容器宽高计算缩放比(而非整个窗口)
  24. const parentWidth = el.parentElement.clientWidth;
  25. const parentHeight = el.parentElement.clientHeight;
  26. const widthRatio = parentWidth / baseWidth;
  27. const heightRatio = parentHeight / baseHeight;
  28. const scale = Math.min(widthRatio, heightRatio); // 取最小缩放比防止溢出
  29. el.style.transform = `scale(${scale}) translate(-50%, -50%)`;
  30. el.style.transformOrigin = 'top left';
  31. }
  32. }
  33. };
  34. </script>
  35. <style scoped>
  36. .container {
  37. width: 100vw;
  38. height: 100vh;
  39. display: flex;
  40. justify-content: center;
  41. align-items: flex-start;
  42. overflow: hidden;
  43. background-color: #0f172a;
  44. }
  45. .scale-content {
  46. position: relative;
  47. width: 1920px;
  48. height: 1080px;
  49. transform-origin: top left;
  50. }
  51. </style>