vue 大屏等比缩放适配方法
大屏适配方案之一,根据设计稿尺寸,固定容器尺寸,内容完全按设计稿大小开发,可保持比例居中显示。
//windowScale.js export function useIndex(appRef,fill) { // * appRef指向最外层容器 // * 定时函数 let timer = null // * 默认缩放值 const scale = { width: '1', height: '1' } // * 设计稿尺寸(px) const baseWidth = 1920 const baseHeight = 1080 // * 需保持的比例(默认2) const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5)) // const baseProportion = 2 const calcRate = () => { // 当前宽高比 const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5)) if(fill){//是否满屏拉伸 scale.width = (window.innerWidth / baseWidth) scale.height = (window.innerHeight / baseHeight) appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)` return } if (appRef) { if (currentRate > baseProportion) { // 表示更宽 scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5) scale.height = (window.innerHeight / baseHeight).toFixed(5) appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)` } else { // 表示更高 scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5) scale.width = (window.innerWidth / baseWidth).toFixed(5) appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)` } } } const resize = () => { clearTimeout(timer) timer = setTimeout(() => { calcRate() }, 100) } // 改变窗口大小重新绘制 const windowDraw = () => { window.addEventListener('resize', resize) } return { appRef, calcRate, windowDraw } }
使用
<template> <div class="container" ref="appRef"></div> </template> <script setup> import { useIndex } from "@/utils/windowScale.js";
const appRef = ref(null); const { calcRate, windowDraw } = useIndex(appRef.value, false); calcRate(); windowDraw(); </script> <style> .container{ width: 1920px; height: 1080px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); transform-origin: left top; transition: all 0.28s; } </style>
道阻且长,行则将至!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通