js自动缩放页面,html自动缩放页面,大屏自动缩放页面,数字看板自动缩放页面,大数据看板自动缩放页面
由纯JS实现
html代码
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no">
<title>缩放</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
color: rgb(0, 0, 0);
background-color: #1d2553;
}
.main {
width: 1920px;
height: 1080px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform-origin: left top;
background-color: beige;
}
.main img{
width: 600px;
height: auto;
max-width: 100%;
max-height: 100%;
}
</style>
</head>
<body>
<div class="main" id="main">
<h1>缩放</h1>
<img src="./img/Mercedes_Logo_19.jpg" alt="">
</div>
<script type="module">
import useDraw from '../js/useDraw.js';
console.log(useDraw);
useDraw(document.getElementById('main'));
</script>
</body>
</html>
js代码
useDraw.js
javascript
const useDraw = (appRef) => {
// * 指向最外层容器
// let appRef;
// * 定时函数
let timer;
// * 默认缩放值
const scale = {
width: '1',
height: '1',
}
// * 设计稿尺寸(px)
const baseWidth = 1920
const baseHeight = 1080
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
const calcRate = () => {
// 当前宽高比
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%)`
}
}
}
calcRate()
const resize = () => {
clearTimeout(timer)
timer = setTimeout(() => {
calcRate()
}, 200)
}
window.addEventListener('resize', resize)
// 改变窗口大小重新绘制
const unWindowDraw = () => {
window.removeEventListener('resize', resize)
}
}
export default useDraw;