- 首先创建一个a.js
const scale = {
width: '1',
height: '1',
}
const baseWidth = 1920
const baseHeight = 1080
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 chartHomeRef = this.$refs["chartHomeRef"]
if (!chartHomeRef) return
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
if (chartHomeRef) {
if (currentRate > baseProportion) {
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
scale.height = (window.innerHeight / baseHeight).toFixed(5)
chartHomeRef.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)
chartHomeRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
}
}
},
resize () {
clearTimeout(this.drawTiming)
this.drawTiming = setTimeout(() => {
this.calcRate()
}, 200)
}
},
}
- 在要使用的地方引入如下
2.1、在要使用的vue页面添加ref="chartHomeRef"
2.2、script俩面引入上面创建的js文件
import a from "@/utils/a";
mixins: [a],