Vue大屏幕等比例缩放

文章介绍了如何在Vue.js应用中创建一个名为drawMixin.js的混入组件,该组件用于处理屏幕适配,特别是在不同设备上进行等比例缩放。它基于设计稿尺寸和窗口宽高比动态计算缩放值,以确保内容始终按比例显示。当窗口大小改变时,会通过定时器更新布局,维持最佳视觉效果。
摘要由CSDN通过智能技术生成

使用混入Mixin

在utils文件夹下新建drawMixin.js 文件,实现等比例缩放代码如下

// 屏幕适配 mixin 函数

// * 默认缩放值
const scale = {
    width: '1',
    height: '1'
}

// *设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080

// *需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))

export default {
    data() {
        return {
            // 定时函数
            drawTiming: null
        }
    },
    mounted() {
        this.calcRate()
        window.addEventListener('resize', this.resize)
    },
    beforeDestory() {
        window.removeEventListener('resize', this.resize)
    },
    methods: {
        calcRate() {
            const appRef = this.$refs["appRef"]
            if(!appRef) return
            // 当前宽高比
            const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
            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%)`
                }
            }
        },
        resize() {
            clearTimeout(this.drawTiming)
            this.drawTiming = setTimeout(() => {
                this.calcRate()
            }, 200)
        }
    }
} 

在App.vue页面引入

import drawMixin from '@/utils/drawMixin.js'
export default{
    name: 'App',
    mixins: [drawMixin],
    setup() {
        return {}
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值