大屏scale适配,解决地图点击事件会偏移

1,187 阅读1分钟

社区内的某大佬的方案

实现适配工具,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)
  },
  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 () {
      clearTimeout(this.drawTiming)
      this.drawTiming = setTimeout(() => {
        this.calcRate()
      }, 200)
    }
  },
}

自己的方案

  refreshScale() {
        let baseWidth = document.documentElement.clientWidth;
        let baseHeight = document.documentElement.clientHeight;
        let appStyle = document.getElementById('dataScreen').style;
        let realRatio = baseWidth / baseHeight;
        let designRatio = 16 / 9;
        let scaleRate = baseWidth / 1920;
        if (realRatio > designRatio) {
          scaleRate = baseHeight / 1080;
        }
        console.log('scaleRate', scaleRate);
        appStyle.transformOrigin = 'left top';
        appStyle.transform = `scale(${scaleRate}) translateX(-50%)`;
        appStyle.width = `${baseWidth / scaleRate}px`;
        // 重点:还原地图的scale比例
        this.scaleStyle = {
          width: 100 * scaleRate + '%',
          height: 100 * scaleRate + '%',
          transform: `scale(${1 / scaleRate}, ${1 / scaleRate} ) `,
          transformOrigin: 'left top'
        };
      }