react 大屏根据屏幕分辨率缩放

发布于:2025-03-26 ⋅ 阅读:(37) ⋅ 点赞:(0)

记录,以防忘记

const DataLargeScreen = () => {
    const layoutRef = useRef<any>();
    // ui稿宽度
    const width = useRef(1920).current;
    // ui稿高度
    const height = useRef(1080).current;
    const [scaleValue, setScaleValue] = useState(1);
    const useWhichScaleValue = () => {
        const innerWidth = window.innerWidth;
        const innerHeight = window.innerHeight;
        const scaleW = innerWidth / width;
        const scaleH = innerHeight / height;
        setScaleValue(Math.min(scaleW, scaleH));
    };
    useEffect(() => {
        useWhichScaleValue();
        // 节流 lodashjs
        window.addEventListener('resize', _.throttle(useWhichScaleValue, 300));
        // window.addEventListener('resize', useWhichScaleValue)
        return () => {
            window.removeEventListener('resize', useWhichScaleValue);
        };
    }, []);
    useEffect(() => {
        const layoutBox = layoutRef.current;
        if (layoutBox) {
            layoutBox.style.setProperty('--scale', scaleValue);
        }
    }, [scaleValue]);

    return (
        <div className="bg-layout" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', width: '100vw', height: '100vh' }}>
            <div className="layout" ref={layoutRef}>
                <ScreenContent />
            </div>
        </div>
    );
};

export default DataLargeScreen;

scss

// 缩放时的背景
.bg-layout {
    background-image: url('~@@/assets/img/dataLargeScreen/largeScreenBg.png');
    background-size: 100% 100%;
    overflow: hidden;
}
.layout {
    // overflow: hidden;
    font-size: 12px;
    color: #fff;
    // font-size: 14px;
    // background-color: aqua;
    width: 1920px;
    height: 1080px;
    background-image: url('~@@/assets/img/dataLargeScreen/largeScreenBorder.png');
    // background-repeat:repeat-x;
    background-size: 100% 100%;
    background-position: center;
    transform: scale(var(--scale));
}