vue3版本
<!--
* @Author: yangzihua
* @Date: 2024-04-12 15:26:36
* @LastEditors: yangzihua
* @LastEditTime: 2024-04-12 16:07:50
* @Description:
-->
<template>
<div
class="main-scale"
:style="{ width: innerWidth + 'px', height: innerHeight + 'px', backgroundColor: '#010916' }"
>
<div class="board" :style="{ transform: `scale(${getScale()})` }">
<slot></slot>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
let innerWidth = ref(window.innerWidth);
let innerHeight = ref(window.innerHeight);
onMounted(() => {
window.addEventListener('resize', handleResize);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
});
function getScale() {
const widthBg = 1920;
const heightBg = 1080;
const widthScale = innerWidth.value / widthBg;
const heightScale = innerHeight.value / heightBg;
return Math.min(widthScale, heightScale);
}
function handleResize() {
innerWidth.value = window.innerWidth;
innerHeight.value = window.innerHeight;
}
</script>
<style scoped>
.main-scale {
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
}
.board {
flex: 0 0 auto;
}
</style>
react版本-类组件
import classNames from 'classnames';
import React from 'react';
import styles from './index.less';
class Scale extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
};
}
componentDidMount() {
window.addEventListener('resize', this.listenWindow);
return () => {
document.removeEventListener('resize', this.listenWindow);
};
}
listenWindow = () => {
this.setState({
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
});
};
getScale = () => {
const { widthBg = 1920, heightBg = 1080 } = this.props;
const widthScale = window.innerWidth / widthBg;
const heightScale = window.innerHeight / heightBg;
return widthScale > heightScale ? heightScale : widthScale;
};
render() {
const { children, mainColor = '#fff', boardStyle } = this.props;
const scaleValue = this.getScale();
const { innerWidth, innerHeight } = this.state;
return (
<div
className={styles.main}
style={{
width: innerWidth,
height: innerHeight,
backgroundColor: mainColor,
}}
>
<div
className={classNames(styles.board, boardStyle)}
style={{
transform: `scale(${scaleValue})`,
}}
>
{children}
</div>
</div>
);
}
}
export default Scale;
// index.less
.main {
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto;
}
.board {
flex: 0 0 auto;
}