【Echarts】Echarts在不同屏幕分辨率下不同配置

文章讲述了如何在Echarts图表中处理低分辨率下刻度标签的旋转问题,以及当图例文字过长时的裁剪和tooltip的启用,同时介绍了如何让图表适应屏幕大小变化,包括响应式布局和使用element-resize-detector库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、图表横坐标:分辨率低的情况下,刻度标签旋转的角度,在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

父组件:

       <div style="width:50%; margin:0 10px 0 0">
                <h6>销售额</h6>
                <div class="salesChart">
                  <el-table
                    v-loading="loading"
                    :data="isFormList"
                    :row-class-name="setRowClass"
                    :cell-class-name="setCellClass"
                    style="width: 45%;">
                    <el-table-column
                      :formatter="formatIndex"
                      label="排名"
                      header-align="center"
                      align="center"
                      min-width="25%"/>
                    <el-table-column
                      prop="class_name"
                      label="部门"
                      align="center"
                      header-align="center"
                      min-width="38%"
                    />
                    <el-table-column
                      align="right"
                      prop="sales_per"
                      min-width="37%"
                      header-align="center"
                      label="占比">
                      <template slot-scope="scope">
                        <span v-if="scope.row.sales_per">{{ scope.row.sales_per }}%</span>
                      </template>
                    </el-table-column>
                  </el-table>
                  <!--***********图表组件***********-->
                  <monthMain :is-form-list="isFormList" :height="month_sales_height" :style="{'width': '55%','height':month_sales_height+'px'}"/>
                  <!--                  <div id="main" style="width: 55%"/>-->
                </div>

              </div>

子组件:

<template>
  <div id="main1" :style="{height:height,width:width}"/>
</template>

<script>
import { formatNumToTen } from '../../../../utils/methods'
// 引入 ECharts 主模块
// var echarts = require('echarts/lib/echarts')
// 引入柱状图
require('echarts/lib/chart/bar')
// 引入折线图
require('echarts/lib/chart/line')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
// require('echarts/lib/component/title');
require('echarts/lib/component/toolbox')
require('echarts/lib/component/legend')
export default {
  name: 'MonthMain',
  props: {
    isFormList: {
      type: Array,
      default: () => {
        return []
      }
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  watch: {
    isFormList: {
      handler(newName, oldName) {
        this.drawChart()
      }
    }
  },
  mounted() {
    this.drawChart()
  },
  methods: {
    drawChart() {
      // 基于准备好的dom,初始化echarts实例
      const myChart = this.$echarts.init(document.getElementById('main1'))

      const result = this.isFormList.map(a => a.sales)
      const result2 = this.isFormList.map(a => a.sales_per + '%')
      const result3 = this.isFormList.map(a => a.class_name)

      for (var i = 0; i < result.length / 2; i++) {
        var temp = result[i]
        result[i] = result[result.length - 1 - i]
        result[result.length - 1 - i] = temp
      }
      for (var i = 0; i < result2.length / 2; i++) {
        var temp = result2[i]
        result2[i] = result2[result2.length - 1 - i]
        result2[result2.length - 1 - i] = temp
      }
      for (var i = 0; i < result3.length / 2; i++) {
        var temp = result3[i]
        result3[i] = result3[result3.length - 1 - i]
        result3[result3.length - 1 - i] = temp
      }
      //********************修改此处********************************************
      // 获取当前窗口大小
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      // 判断图表是否小于一定值
      if (windowWidth < 1800 && windowHeight < 1000) {
        var grid = {
          top: '50px',
          left: '3%',
          right: '15%',
          bottom: '3%',
          containLabel: true
        }
        // 设置 xAxis 属性
        var xAxis = {
          type: 'value',
          boundaryGap: [0, 0.01],
          axisLabel: {
            interval: 0,
            rotate: -30
          }
        }
      } else {
        grid = {
          top: '49px',
          left: '3%',
          right: '9%',
          bottom: '3%',
          containLabel: true
        }
        // 大屏幕下xAxis属性
        xAxis = {
          type: 'value',
          boundaryGap: [0, 0.01]
        }
      }
      //***************************新增结束*************************************
      // 指定图表的配置项和数据
      const option = {
        title: {
          text: '',
          subtext: ''
        },
        color: ['#FF8DAD'],
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器,坐标轴触发有效
            type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
          },
          formatter: function(datas) {
            // var name = ''
            var index = datas[0].dataIndex
            datas[0].name = result3[index]
            var res = datas[0].name + '<br/>', val
            for (var i = 0, length = datas.length; i < length; i++) {
              val = formatNumToTen(datas[i].value) + '元'
              res += datas[i].marker + datas[i].seriesName + ':' + val + '<br/>'
            }
            return res
          }
        },
        legend: {
          data: []
        },
        backgroundColor: '#fff',
        //***********************修改此处*****************************************
        grid: grid,
        xAxis: xAxis,
        //***********************新增结束*****************************************
        yAxis: {
          type: 'category',
          data: result2,
          axisLabel: {
            show: false,
            interval: 0
          }
        },
        series: [
          {
            name: '月销售额',
            type: 'bar',
            barWidth: '25px',
            data: result

          }

        ]
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
      // getDom() 获取 ECharts 实例容器的 dom 节点
      const chartName = this.$echarts.init(document.getElementById('main1'))
      chartName.getDom().style.height = this.height + 'px'
      // chartName.getDom().childNodes[0].style.height = this.month_sales_height + 'px'
      // chartName.getDom().childNodes[0].childNodes[0].setAttribute('height', this.month_sales_height)
      // chartName.getDom().childNodes[0].childNodes[0].style.height = this.month_sales_height + 'px'
      chartName.resize()
    }
  }
}
</script>

<style scoped>

</style>


2、图表图例:在 legend 文字超过6个字的时候对文字做裁剪并且开启 tooltip

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

myEcharts() {
      this.cityComplementBar = this.$echarts.init(document.getElementById('Chart1'))
      var data = []
      if (this.topsum) {
        for (const da in this.topsum) {
          data[da] = { value: this.topsum[da].sales, name: this.topsum[da].store_name }
        }
      }
       //************************修改此处******************************************************
      // 获取当前窗口大小
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      // 判断图表是否小于一定值
      if (windowWidth < 1800 && windowHeight < 1000) {
        // 设置 legend 属性
        var legend = {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 30,
          bottom: 20,
          // 在 legend 文字超过6个字的时候对文字做裁剪并且开启 tooltip
          formatter: name => name.length > 6 ? name.substr(0, 6) + '...' : name,
          tooltip: {
            show: true
          }
        }
      } else {
        // 大屏幕下legend属性,文字正常展示
        legend = {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 30,
          bottom: 20
        }
      }
       //****************************新增结束**************************************************

      const option1 = {
        tooltip: {
          trigger: 'item',
          formatter: function(p) {
            var value = p.value
            var percent = p.percent
            if (value === null || value === undefined) {
              value = ''
            }
            if (percent === null || percent === undefined) {
              percent = ''
            }
            return p.name + ':' + '<br/>' + formatNumToTen(value) + '元' + '(' + percent + '%' + ')'
          }
        },
        //***********修改此处*******************
        legend: legend,
        //***********新增结束*******************
        color: getColorListByTen(10),
        series: [
          {
            name: '销售额',
            type: 'pie',
            radius: ['55%', '65%'],
            center: ['30%', '50%'],
            data: data,
            zIndex: 1,
            label: {
              show: true,
              position: 'center',
              formatter: function(params) {
                // return ''
                // if (params.dataIndex === 0) {
                if(params.name.length>=7){
                  // return ''
                  return '{p|' + params.percent + '%}' + '\n{nm|' + params.name.substring(0,8) + '\n'+ params.name.substring(8) + '}'
                }else{
                  return '{p|' + params.percent + '%}' + '\n{nm|' + params.name + '\n'+ '    ' + '}'
                }
                // } else {
                //   return ''
                // }
              },
              emphasis: {
                formatter: function(params) {
                  if(params.name.length>7){
                    return '{p|' + params.percent + '%}' + '\n{nm|' + params.name.substring(0,8) + '\n'+ params.name.substring(8) + '}'
                  }else{
                    return '{p|' + params.percent + '%}' + '\n{nm|' + params.name + '\n'+ '    ' +'}'
                  }
                }
              },
              rich: {
                p: {
                  color: '#323233',
                  fontSize: 16,
                  backgroundColor: '#fff',
                  width: 130,
                  height: 30,
                  fontWeight: 600
                },
                nm: {
                  color: '#323233',
                  fontSize: 15,
                  backgroundColor: '#fff',
                  width: 130,
                  height: 20
                }
              }
            }
          }
        ]
      }
      this.cityComplementBar.setOption(option1)
    },

参考文章:

1、使echarts图表随容器或屏幕变化而改变大小

使echarts图表随容器或屏幕变化而改变大小
分两种情况

一、屏幕大小变化导致echarts容器大小变化

如缩小浏览器页面,竖屏变横屏

this.myChart1 = echarts.init(document.getElementById("mychart"));
this.myChart1.setOption(option);
//随着屏幕大小调节图表
window.addEventListener("resize", () => {
     this.myChart1.resize();
});

详解代码:
在这里插入图片描述


二、屏幕大小不变但echarts容器大小变化

如菜单的折叠展开导致的主面板宽度变化,但浏览器屏幕大小是没有变的,这种情况下第一种方法不管用,则使用下述方法:

1.引入插件

npm install element-resize-detector --save

2.在所需页面导入

import elementResizeDetectorMaker from "element-resize-detector";

3.在mounted里使用

let erd = elementResizeDetectorMaker();
let that = this;
erd.listenTo(document.getElementById("echarts-box"), (element) => {
  that.$nextTick(() => {
    //使echarts尺寸重置
    that.myChart1.resize();
    that.myChart2.resize();
  });
});

2、Echarts图表的使用以及如何适应屏幕变化

Echarts图表的使用以及如何适应屏幕变化
在这里插入图片描述

🚀写在最后

希望我的分享能够帮助到更多的人,如果觉得我的分享有帮助的话,请大家一键三连支持一下哦~
❤️原创不易,期待你的关注与支持~
点赞👍+收藏⭐️+评论✍️
😊之后我会继续更新前端学习小知识,关注我不迷路~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小魔女千千鱼

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值