Files
app-govern/common/js/drawMixin.js

72 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-07-24 08:47:20 +08:00
// 屏幕适配 mixin 函数
// * 默认缩放值
const scale = {
width: '1',
height: '1',
};
// * 设计稿尺寸px
const baseWidth = 375;
const baseHeight = 667;
// * 需保持的比例默认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'];
const fatherRef = this.$refs['fatherRef'];
if (!appRef) return;
// 当前宽高比
const currentRate = parseFloat(
(fatherRef.offsetWidth / fatherRef.offsetHeight).toFixed(5)
);
if (appRef) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = (
(fatherRef.offsetHeight * baseProportion) /
baseWidth
).toFixed(5);
scale.height = (
fatherRef.offsetHeight / baseHeight
).toFixed(5);
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
} else {
// 表示更高
scale.height = (
fatherRef.offsetWidth /
baseProportion /
baseHeight
).toFixed(5);
scale.width = (fatherRef.offsetWidth / baseWidth).toFixed(
5
);
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
}
}
},
resize() {
clearTimeout(this.drawTiming);
this.drawTiming = setTimeout(() => {
this.calcRate();
}, 200);
},
},
};