scale.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // 记录防抖定时器和绑定的函数,方便销毁时解绑
  2. let resizeTimer = null;
  3. let boundResizeFn = null;
  4. export function initScale(options) {
  5. const {
  6. wrapperId = 'screen-wrapper',
  7. designWidth = 1920,
  8. designHeight = 1080
  9. } = options;
  10. const wrapper = document.getElementById(wrapperId);
  11. if (!wrapper) {
  12. console.error(`未找到ID为 ${wrapperId} 的大屏容器`);
  13. return;
  14. }
  15. // 核心计算逻辑
  16. const calcAndApplyScale = () => {
  17. const clientWidth = window.innerWidth;
  18. const clientHeight = window.innerHeight;
  19. const scaleX = clientWidth / designWidth;
  20. const scaleY = clientHeight / designHeight;
  21. // 取最小比例,保证等比缩放且全部可见
  22. const scale = Math.min(scaleX, scaleY);
  23. // 应用缩放,配合 CSS 的绝对定位居中
  24. wrapper.style.transform = `scale(${scale}) translate(-50%, -50%)`;
  25. };
  26. // 防抖处理:避免窗口拖拽时频繁触发重绘引发卡顿
  27. boundResizeFn = () => {
  28. if (resizeTimer) clearTimeout(resizeTimer);
  29. resizeTimer = setTimeout(() => {
  30. calcAndApplyScale();
  31. }, 100);
  32. };
  33. // 1. 初始化执行一次
  34. calcAndApplyScale();
  35. // 2. 挂载监听
  36. window.addEventListener('resize', boundResizeFn);
  37. }
  38. // 销毁函数:在 Vue 组件销毁前调用,防止内存泄漏
  39. export function destroyScale() {
  40. if (boundResizeFn) {
  41. window.removeEventListener('resize', boundResizeFn);
  42. boundResizeFn = null;
  43. }
  44. if (resizeTimer) {
  45. clearTimeout(resizeTimer);
  46. resizeTimer = null;
  47. }
  48. }