效果图如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- <script src="echarts.min.js"></script> -->
<style>
.echart-box {
width: 453px;
height: 252px;
border: 1px solid red;
}
.echart-title {
width: 437px;
height: 36px;
line-height: 36px;
padding-left: 16px;
font-size: 18px;
color: #2ad5f7;
border: solid 1px #294c66;
}
#echart-bar {
width: 100%;
height: 214px;
border: 1px solid green;
}
</style>
</head>
<body>
<div class="echart-box">
<div class="echart-title">成绩排名</div>
<div id="echart-bar"></div>
</div>
<div id='picinfo'></div>
<script src="./node_modules/echarts/dist/echarts.min.js"></script>
<script src='./node_modules/echarts/dist/echarts.js'></script>
<script>
var myChart = echarts.init(document.getElementById('echart-bar'));
// 指定图表的配置项和数据
var barOption = {
dataset: {
source: [ // 可从后台取值动态传入
['amount', 'name'],
[58212, '语文'],
[78254, '数学'],
[41032, '英语'],
[12755, '生物'],
[20145, '物理'],
[79146, '化学'],
]
},
grid:{
left:"16%",
top:"20px",
bottom:"20px",
},
tooltip: {
show:true,
trigger: 'axis',
axisPointer:{
type:'none',
},
},
toolbox:{
show:true,
orient:'horizontal',
itemSize:15,
itemGap:10,
feature :{
show:true,
dataView:{
readOnly:false,
},
magicType:{
type:['bar','line']
},
saveAsImage:{
name:"横向柱状图",
type:'png',
title:'保存为图片',
// icon:'image://static/image/download.png', // 报错图片跨域,原因:图片存储在本地时默认没有域名,使用getImageData()时,浏览器会判定为跨域 解决办法:将图片放在服务器上
excludeComponent:['toolbox'] // 下载文件时不显示工具栏
},
}
},
xAxis: {name: '',show:false},
yAxis: {
type: 'category',
nameGap:"11px",
boundaryGap:["14px","14px"],
axisLine:{
show :false // 不显示轴线
},
axisTick:{
show:false // 不显示刻度
},
nameLocation:"center",
axisLabel : {
show:true,
textStyle: {
color: "#44eefe",
fontSize:"14px"
},
},
},
series: [
{
type: 'bar',
encode: { // 定义data的哪个维度编码成啥样
x: 'amount',
y: 'name'
},
barWidth:"7px",
barCategoryGap:"25px", // 柱间距
nameTextStyle:{
color:"red",
fontSize:"14px"
},
itemStyle: {
normal:{
barBorderRadius:10,
color: function (params){
var colorList = ["#2aa2f7","#00d395","#00f2fd","#ffb000","#a027fd","#ac0b85"];
return colorList[params.dataIndex];
}
},
},
label: {
show: true,
color:" #c9c9c9",
position: 'right'
},
}
]
};
myChart.setOption(barOption);
</script>
</script>
</body>
</html>
遇到问题:
1.saveAsImage设置icon时,把图片存在了本地,引用相对路径出错,导致没有显示
注:填写相对路径的时候前面的"image://"不能丢.正确写法:“image://”+相对路径/绝对路径
icon:'image://static/image/download.png',
2.icon显示出来之后点击过后报错图片跨域:
出错原因:图片存储在本地时默认没有域名.在使用echarts包里面的getImageData()的时候浏览器判定为跨域.
解决办法:把静态资源文件置于服务器 或者直接使用Http路径去访问图片.
下载图片为