echarts动态改变图表的大小

echarts动态改变图表的大小

echarts5以上的版本,echarts容器支持直接设定百分比宽高,但是仍然会有低版本的一个问题,就是浏览器尺寸变动的时候,echarts容器不会响应式的变化。

为了解决这个问题,有了如下解决方案:

  • 首先echarts容器外要放置一个父元素
  <div ref="ct" style="height: 100%; width: 100%">
    <div ref="charts" style="height: 100%; width: 100%"></div>
  </div>

其中父元素一定要使用行内样式的方式设定宽高。

  • 重新刷新尺寸的工具函数:

    /**
     *@description 为图表计算高度
     *@param container 父容器
     *@param charts echarts对象
     *@param offsetX 横轴偏移,可不填,默认50px
     *@param offsetY 纵轴偏移,可不填,默认70px
    */
    export function chartssize(container, charts, offsetX =50 , offsetY = 70) {
      function getStyle(el) {
        if (window.getComputedStyle) {
          const doc = window.getComputedStyle(el);
          const height = parseInt(doc.height);
          const width = parseInt(doc.width);
          return {height, width};
    
        } else {
          return {height: container.clientHeight, width:container.clientWidth};
        }
      }
      const {height, width} = getStyle(container, null)
      charts.resize({width: parseInt(width - offsetX), height: parseInt(height - offsetY)})
    }
    
  • 以VUE为例:

    使用:

    import * as echarts from "echarts";
    import { option } from "./config.js";
    import { chartssize } from "@/utils/resize";
    export default {
      data() {
        return {
          charts: {},
        };
      },
      created() {
        this.$nextTick(() => {
          this.echartsinit();
        });
      },
      mounted() {
          const ct = this.$refs["ct"];
          window.addEventListener("resize", () => {
              chartssize(ct, this.charts, 0, 0);
          });
          // window.onresize = () => {
          //   const ct = this.$refs["ct"];
          //   chartssize(ct, this.areaLine, 0, 0);
          // };
      },
      methods: {
        echartsinit() {
          if (process.client) {
            this.charts = echarts.init(this.$refs["charts"]);
            this.charts.setOption(option);
          }
        },
      },
    };
    

    注意:mounted里的方法为重新设置echarts容器的方法。实际上就是监听窗口的resize事件,在这里有两种方式监听resize事件。一种是重写window.onresize,但是使用这种方式会有一个问题,如果同一个页面内有多个echarts图表,那么只有最后一个被渲染的才会生效。这个时候只要使用window.addEventListener的方式即可解决

本文里并未对resize的监听进行优化,会导致页面中如果图表过多,浏览器卡顿的情况,针对resize的函数节流,请看我的另一篇文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cRack_cLick

感谢你的支持!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值