| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- // 记录防抖定时器和绑定的函数,方便销毁时解绑
- let resizeTimer = null;
- let boundResizeFn = null;
- export function initScale(options) {
- const {
- wrapperId = 'screen-wrapper',
- designWidth = 1920,
- designHeight = 1080
- } = options;
- const wrapper = document.getElementById(wrapperId);
- if (!wrapper) {
- console.error(`未找到ID为 ${wrapperId} 的大屏容器`);
- return;
- }
- // 核心计算逻辑
- const calcAndApplyScale = () => {
- const clientWidth = window.innerWidth;
- const clientHeight = window.innerHeight;
- const scaleX = clientWidth / designWidth;
- const scaleY = clientHeight / designHeight;
- // 取最小比例,保证等比缩放且全部可见
- const scale = Math.min(scaleX, scaleY);
- // 应用缩放,配合 CSS 的绝对定位居中
- wrapper.style.transform = `scale(${scale}) translate(-50%, -50%)`;
- };
- // 防抖处理:避免窗口拖拽时频繁触发重绘引发卡顿
- boundResizeFn = () => {
- if (resizeTimer) clearTimeout(resizeTimer);
- resizeTimer = setTimeout(() => {
- calcAndApplyScale();
- }, 100);
- };
- // 1. 初始化执行一次
- calcAndApplyScale();
- // 2. 挂载监听
- window.addEventListener('resize', boundResizeFn);
- }
- // 销毁函数:在 Vue 组件销毁前调用,防止内存泄漏
- export function destroyScale() {
- if (boundResizeFn) {
- window.removeEventListener('resize', boundResizeFn);
- boundResizeFn = null;
- }
- if (resizeTimer) {
- clearTimeout(resizeTimer);
- resizeTimer = null;
- }
- }
|