drawMixin.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // 屏幕适配 mixin 函数
  2. // * 默认缩放值
  3. const scale = {
  4. width: '0.5',
  5. height: '0.5',
  6. }
  7. // * 设计稿尺寸(px)
  8. const baseWidth = 1920;
  9. const baseHeight = 1080;
  10. // * 需保持的比例(默认1.77778)
  11. const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));
  12. export default {
  13. data() {
  14. return {
  15. // * 定时函数
  16. drawTiming: null
  17. }
  18. },
  19. mounted () {
  20. this.$nextTick(() => {
  21. //进入触发
  22. this.calcRate();
  23. window.addEventListener('resize', this.resize);
  24. });
  25. },
  26. created() {
  27. },
  28. updated(){
  29. },
  30. beforeCreate() {
  31. },
  32. beforeUpdate() {
  33. },
  34. beforeDestroy () {
  35. window.removeEventListener('resize', this.resize);
  36. },
  37. methods: {
  38. calcRate () {
  39. //拿到整个页面元素
  40. const appRef = this.$refs["appRef"];
  41. console.log("this",this.$refs);
  42. //如果没有值就结束
  43. if (!appRef) return;
  44. // 当前宽高比
  45. const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5));
  46. //判断:如果有值代表页面变化了
  47. if (appRef) {
  48. //判断当前宽高比例是否大于默认比例
  49. if (currentRate > baseProportion) {
  50. // 如果大于代表更宽了,就是放大了
  51. //那么把默认缩放的宽高改为:同比例放大
  52. scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5) * 0.95;
  53. scale.height = (window.innerHeight / baseHeight).toFixed(5) * 0.95;
  54. console.log(scale.width,scale.height,'放大');
  55. //整个页面的元素样式,缩放宽高用当前同比例放大的宽高
  56. appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -40%)`;
  57. } else {
  58. // 如果不大于默认比例代表缩小了。
  59. //那么把默认缩放的宽高改为:同比例缩小
  60. scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5) * 0.95 ;
  61. scale.width = (window.innerWidth / baseWidth).toFixed(5) * 0.95 ;
  62. console.log(scale.width,scale.height,'缩小');
  63. //整个页面的元素样式,缩放宽高用当前同比例放大的宽高
  64. appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -40%)`;
  65. }
  66. }
  67. },
  68. resize () {
  69. clearTimeout(this.drawTiming);
  70. this.drawTiming = setTimeout(() => {
  71. this.calcRate();
  72. }, 2000);
  73. }
  74. },
  75. }