如何让echart铺满设置的尺寸

在使用echart进行自适应时,给echart设置了100%,但是echart图表的大小并没有铺满100%;
在这里插入图片描述
样式的话,我是使用less,在页面渲染的时候,即使设置了尺寸,但会有一定的延迟,拿到的echart尺寸并是不我想要的;
可以通过让echart延迟显示,达到想要的效果;

  • 提供一个容器
    在这里插入图片描述
 constructor(props) {
    super(props);
    this.state = {
      loading: true,
      type: "供水",
    };
    this.echartbox1 = React.createRef();
    this.echartInit1 = null;
    this.throttleTimer = null;
  }

在这里插入图片描述

  • 在页面一渲染的时候进行设置
    在这里插入图片描述
 componentDidMount() {
    // console.info(this.echartbox1.current.offsetHeight);
    window.addEventListener("resize", this.onresize);

    // 1000ms后loading为false
    setTimeout(() => {
      this.setState({
        loading: false
      });
    }, 1000);
    // 由于less样式会有一定的延迟,echart图表的大小会有一定的变化
    setTimeout(() => {
      console.info(this.echartbox1.current.offsetHeight);
      // 延迟饼图的加载,就是让图表铺满所设置的尺寸
      this.setChart();
    }, 0);
  }
  • 自适应
    在这里插入图片描述
// 监听窗口resize
  onresize = () => {
    // 使echart图表随窗口的大小进行变化
    this.echartInit1 && this.echartInit1.resize();
  }

在这里插入图片描述

// 设置饼图
  setChart = () => {
    if (!this.echartInit1) this.echartInit1 = echarts.init(this.echartbox1.current);

    this.echartInit1.setOption(this.eo1());
    this.echartInit1.resize();
  }
  • 图表的配置项
 // 图表的配置项
  eo1 = () => {
    const lgdata = [
      { name: "100及以下", icon: "roundRect" },
      { name: "100-300(含)", icon: "roundRect" },
      { name: "300-600(含)", icon: "roundRect" },
      { name: "600以上", icon: "roundRect" },
    ];
    let options = {
      color: ["#1676fe", "#FAB20C ", "#FA6119", "#9F51F0"],
      tooltip: {
        trigger: "item",
        fommatter: "{a} : {b}",
        confine: true,//将此权限打开后tooltip将不再溢出
      },
      // 图列组件
      legend: {
        data: lgdata,
        // 设置图例的位置
        left: "65%",
        top: "25%",
        orient: "vertical",
        itemWidth: 10,//图例图形的宽度
        itemHeight: 10,
      },
      series: {
        type: "pie",
        // 饼图的位置
        center: ["35%", "50%"],
        // 饼图的大小
        radius: ["0", "75%"],
        data: [{ name: "100及以下", value: 50 },
        { name: "100-300(含)", value: 120 },
        { name: "300-600(含)", value: 350 },
        { name: "600以上", value: 670 },],
        label: {
          normal: {
            show: false,
          },
          emphasis: {
            show: false,
          },
        },
      }
    };
    return options;
  }

通过上面的设置,实现了我想要的效果。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐