【vue】可视化大屏实现固定比例布局(不错位)

4 篇文章 0 订阅

背景
最初方案是使用dataV中的大屏自适应组件,后续发现dataV在不同显示器分辨率下的效果会不一致导致图表内容错位等问题;后续查找资料重新写自适应。

组件封装
resizeMixin.js

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

// * 设计稿尺寸(px)
const baseWidth = 2560;
const baseHeight = 1440;

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

export default {
    data() {
        return {
            drawTiming: null,
        };
    },
    mounted() {
        this.calcRate();
        window.addEventListener('resize', this.resize);
    },
    beforeDestroy() {
        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})`;
                // } else {
                    // 表示更高
                    scale.height = (
                        window.innerWidth /
                        baseProportion /
                        baseHeight
                    ).toFixed(5);
                    scale.width = (window.innerWidth / baseWidth).toFixed(5);
                    appRef.style.transform = `scale(${scale.width}, ${scale.height})`;
                // }
            }
        },
        resize() {
            clearTimeout(this.drawTiming);
            this.drawTiming = setTimeout(() => {
                this.calcRate();
            }, 200);
        },
    },
};

页面使用
js:

import resizeMixin from "@/utils/resizeMixin";

export default {
  mixins: [resizeMixin],

  data() {
    return {}
  },
  ......
}

div:

<template>
  <div class="pane" ref="appRef">
  ......
   </div>
</template>

css:

.pane {
  /*// 设计稿宽高*/
  width: 2560px;
  height: 1440px;
  /*// 盒子水平垂直居中*/
  position: fixed;
  top: 0;
  left: 0;
  transform-origin: left top;
  transform: translate(-50%, -50%);
  overflow: hidden;
}

效果图:
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值