v-scale-screen 原理

v-scale-screen 原理
大屏项目中的适配屏幕大小缩放原理demo还原

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
      
      
            margin: 0px;
            padding: 0px;
        }

        #app {
      
      
            background-color: antiquewhite;
            width: 1920px;
            height: 1080px;
        }
    </style>
</head>

<body>
    <div id="app"></div>
</body>

</html>
<script>

    const autoScale = (selector, option) => {
      
      
        const el = document.querySelector(selector);
        let {
      
       width, height } = option;
        el.style.transformOrigin = 'top left';
        el.style.transition = 'all 0.5s';
        const init = () => {
      
      
            const scaleX = innerWidth / width;
            const scaleY = innerHeight / height;
            //去最小值
            const scale = Math.min(scaleX, scaleY);
            const left = (innerWidth - width * scale) / 2;
            let top = (innerHeight - height * scale) / 2;
            //居中并缩放
            el.style.transform = `translate(${ 
        left}px,${ 
        top}px) scale(${ 
        scale})  `;
        };
        init();
        // window.onresize = () => init;
        // 这里可以写个防抖
        addEventListener('resize', init)
    };


    let option = {
      
      
        width: 1920,
        height: 1080,
    };



    autoScale('#app', option);
</script>

猜你喜欢

转载自blog.csdn.net/qq_43940789/article/details/138450959