Vue实现页面等比缩放

发布于 2022-07-29  81 次阅读


  • 1、现在最外层的div加上
<div
    id="index"
    ref="appRef"
    class="index_home"
    :class="{ pageisScale: isScale }"
  >
</div>
  • 2、CSS样式
#index {
  color: #d3d6dd;
  width: 1920px;
  height: 1080px;
  overflow: hidden;
}
  • 3、先在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,
      isScale: true,
    }
  },
  computed: {

  },
  mounted () {
    if (!this.isScale) {
      return
    }
    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}) 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 () {
      if (!this.isScale) {
        return
      }
      clearTimeout(this.drawTiming)
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}
  • 4、在需要的页面引入
// 先引入刚创建drawMixin.js文件
import drawMixin from "@/utils/drawMixin";
// mixin混入后注册使用
mixins: [drawMixin],