最近项目要用到echarts画图,踩了个自适应的坑,在这里总结一下,首先看bug图
在这里插入图片描述
分析一下:左边的盒子,也就准一等品花颜色得分情况没有出来是因为我最外边的盒子设置的固定宽,如果设置固定宽 echarts是能够自适应的,但是页面会挤在一起,也就是左边 中间 右边的盒子间隔会随着浏览器窗口放大,放大的结果就是浏览器窗口宽度变小了,而盒子固定宽度不变,导致盒子会挤压在一起,布局就不美观了。所以为了自适应,我把盒子的都设成百分比了;
中间和右边的div盒子我就是设置百分比宽,这样设置页面是不会挤在一起了,但是echarts无法自适应,大小固定不变,导致图形超出盒子,也就是现在见到的样子。

这里是解决方法:
1、前提:画布外部的盒子宽和画布的宽都需要设置百分比宽,如果画布还是设置了固定宽,即使加了方法还是不会自适应
2、下面就是方法了
在这里插入图片描述
加我所注释说明的那段代码就行

效果:
在这里插入图片描述
现在就不会挤出去了。
下面是写的一个小demo,可以参考一下

<template>
	<div class="app">
		<div id="data-rh-body" class="data-lf-top" ></div>
	</div>
</template>

<script>
	var echarts=require('echarts')
	export default{
		methods:{
			drawChart2() {
				// 基于准备好的dom,初始化echarts实例
				let myChart = this.$echarts.init(document.getElementById('data-rh-body'));
				// 指定图表的配置项和数据
				let option = {
					grid: {
						//坐标系地板的定位
						left:60,
						bottom:50
					},
					xAxis: {
						type: 'category', //类名轴
						data: ['5', '6', '7','8','9','10'],
						axisLine: {//坐标轴轴线相关设置
							
							lineStyle: {
								color: '#262571'//x轴线颜色设置
							}
						},
						axisLabel: {// 坐标轴刻度标签的相关设置
							show: true,//控制显隐
							textStyle: {
								color: '#6FCEFF',//x轴字体颜色
								fontSize: 20 // 
							}
						},
						axisTick: {
							//x轴刻度相关设置
							show: false
						}
					},
					yAxis: {
						axisLine: {
							//坐标轴轴线相关设置
							lineStyle: {
								color: '#262571'
							}
						},
						axisLabel: {//坐标轴刻度标签的相关设置
							textStyle: {//y轴字体样式设置
								color: '#CFD4EB',
								fontSize:20
							}
						},
						axisTick: {
							//y轴刻度相关设置
							show: false
						},
						splitLine: {//坐标轴在 grid 区域中的分隔线相关设置
							lineStyle: {//线的样式设置
								color: '#262571'
							}
						}
					},
					series: [
						{
							name: '数量',
							type: 'bar',
							data: [50, 125, 10,50,30,15],
							barWidth: 28, //柱图宽度
							itemStyle: {//图形样式相关设置
								normal: {
									//自定义柱形渐变色
									color: new echarts.graphic.LinearGradient(
										0,
										1,
										0,
										0,
										[
											{
												offset: 0,
												color: '#63FFFF' // 0% 处的颜色
											},
											{
												offset: 1,
												color: '#0054FF' // 100% 处的颜色
											}
										],
										false
									),
								}
							}
							
						}
					]
				};
				// 使用刚指定的配置项和数据显示图表。
				myChart.setOption(option);
				window.addEventListener("resize", () => {
				      if(myChart){
						  myChart.resize()
					  }
				})
				 // window.onresize = myChart.resize;
			},
		},
		mounted(){
			this.drawChart2()
		}
	}
</script>

<style scoped>
	.app{
		width: 50%;
		height: 500px;
		background: #000000;
		margin: auto;
	}
	#data-rh-body{
		width: 100%;
		height: 100%;
	}
</style>

Logo

前往低代码交流专区

更多推荐