0、前言
仿照 vue2-scale-box
1、调用示例
<ScreenAutoBox width={1920} height={1080} flat={true}>{/* xxx代码 */}</ScreenAutoBox>
2、组件代码
import { CSSProperties, ReactNode, RefObject, useEffect, useRef, useState } from 'react'//数据大屏自适应函数
const getTransform = (designWidth = 1920, designHeight = 1080, flat = true) => {const w = document.documentElement.clientWidthconst h = document.documentElement.clientHeightif (flat) {//缩放比例(拉伸)return `scaleX(${w / designWidth}) scaleY(${h / designHeight}) translate(-50%, -50%)`} else {// 不拉伸return `scale(${w / h > designWidth / designHeight ? h / designHeight : w / designWidth}) translate(-50%, -50%)`}
}export default function ScreenAutoBox({width = 1920,height = 1080,flat = true, // 是否拉伸children
}: {width?: numberheight?: numberflat?: booleanchildren?: ReactNode
}) {const BoxRef: RefObject<HTMLDivElement> = useRef(null)const [transformValue, setTransformValue] = useState('scaleX(1) scaleY(1) translate(-50%, -50%)')useEffect(() => {setTransformValue(getTransform(width, height, flat))window.onresize = () => setTransformValue(getTransform(width, height, flat))// 销毁监听自适应消失return () => {window.onresize = null}}, [])const style: CSSProperties = {width: width + 'px',height: height + 'px',position: 'fixed',left: '50%',top: '50%',transformOrigin: '0 0',backgroundColor: 'transparent',zIndex: 100}return (<div ref={BoxRef} style={{ ...style, transform: transformValue }}>{children}</div>)
}