JavaScript is required
Blog About

简单实现一个使用scale适配大屏的方法

2024/02/01
5 mins read
See this issue
# Javascript
Back

这几天看到手上大屏项目是封装了缩放包裹vue组件实现的大屏适配,感觉不是很合适,所以自己改成了成原生实现的的方法

主要原理网上有很多,核心是根据设计稿尺寸和当前屏幕尺寸来给容器设置scale比例

# autofit 代码

function autofit(_options){
      const defaultOptions = {
        el:'body',
        scale:1,
        width: 1920,
        height: 1080,
        transition: '0.2s'
      }
      let options = null

      function setOptions() {
        options = Object.assign(defaultOptions, _options)
        if (typeof options.el !== 'string') return
        const el = document.querySelector(options.el);
        if (el) {
          options.el = el
        } else {
          throw new Error('autofit: el is not exist')
        }
      }

      function getScale() {
        // 计算出合适的缩放比
        const { width, height, scale } = options;
        const wh = window.innerHeight / height;
        const ww = window.innerWidth / width;
        return (ww < wh ? ww : wh) * scale;
      }

      function setScale() {
        // 获取到缩放比例,设置它
        const scale = getScale();
        options.el.style.setProperty("--scale", scale);
      }

      function debounce(fn, delay) {
        const delays = delay || 500;
        let timer;
        return function () {
          const th = this;
          const args = arguments;
          if (timer) {
            clearTimeout(timer);
          }
          timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
          }, delays);
        };
      }

      function setInlineStyle() {
        const { el, width, height, transition } = options;
        el.style.width = `${width}px` ;
        el.style.height = `${height}px`;
        el.style.transition = transition
        el.style.transformOrigin = '0 0'
        el.style.transform = 'scale(var(--scale)) translate(-50%, -50%)'
        el.style.position = 'absolute'
        el.style.top = '50%'
        el.style.left = '50%'
        el.style.overflow = "hidden"
        el.style.margin = 0
      }

      (function init() {
        setOptions()
        setInlineStyle()
        setScale()
        window.addEventListener("resize", debounce(setScale))
      })()
    }

# 如何去使用

没有什么太多需求可以直接使用

autofit()

如果需要修改默认配置,则传入_options参数

  • el :缩放容器,默认body
  • scale:缩放比例基准,默认1,
  • width:设计稿宽度,默认1920,
  • height:设计稿高度,默认1080,
  • transition:缩放变化过渡效果,默认’0.2s’

# 效果预览