一、在App.vue的props注入宽高
props: {
width: {
type: String,
default: "1920"
},
height: {
type: String,
default: "1080"
}
},
二、在data中定义style
style: {
width: this.width + "px",
height: this.height + "px",
transform: "scale(1) translate(-50%, -50%)"
}
三、在methods中定义方法
Debounce: (fn, t) => {
const delay = t || 500;
let timer;
return function() {
const args = arguments;
if (timer) {
clearTimeout(timer);
}
const context = this;
timer = setTimeout(() => {
timer = null;
fn.apply(context, args);
}, delay);
};
},
getScale() {
const w = window.innerWidth / this.width;
const h = window.innerHeight / this.height;
return w < h ? w : h;
},
setScale() {
this.style.transform =
"scale(" + this.getScale() + ") translate(-50%, -50%)";
}
四、给html标签动态绑定 style
- 注意:如果宽高不够等比,给最大的盒子一个背景色,下面的例子就是
<div id="app" style="background:linear-gradient(#112550, #0F2C74)">
<div class="ScreenAdapter" :style="style">
<router-view />
</div>
</div>
五、给类名 ScreenAdapter 添加css样式
.ScreenAdapter {
transform-origin: 0 0;
position: absolute;
left: 50%;
top: 50%;
transition: 0.3s;
}
六、在 mounted 中调用 setScale()方法、和使用window.onresize 方法
this.setScale();
window.onresize = this.Debounce(this.setScale, 1000);