一. 前言
项目中遇到了要用图表展示业务数据的需求,于是引入了echarts
———— 一个基于 JavaScript 的开源可视化图表库,echarts
最初由百度开发,后交由阿帕奇基金会孵化。
echarts已经在全球范围内得到了广泛的应用。它能够运行在PC和移动设备上,并且兼容当前的主流浏览器。通过ECharts,开发者可以轻松地创建出各种类型的图表,包括折线图、柱状图、饼图、散点图等,从而帮助用户更好地理解和分析数据。本文给大家
分享一下echarts的基本使用方法。
先看效果图:
二. 使用方法
在我们的页面中引入echarts,准备一个盒子,注意盒子要设置宽度与高度
</template>
<div class='chart-container' ref='myChart'></div>
</template>
<script>
import * as echarts from 'echarts/core';
export default {
mounted() {
this.registerShape();
this.initChart();
},
}
</script>
<style scoped>
.chart-container{
width: 100%;
height: 100%;
}
</style>
我们这里先准备好柱子,使用Canvas
实现柱形
registerShape() {
const offsetX = 11; //这里可调整柱子的宽度
const offsetY = 8;
// 绘制左侧面
const CubeLeft = echarts.graphic.extendShape({
shape: {
x: 0,
y: 0,
},
buildPath: function(ctx, shape) {
const xAxisPoint = shape.xAxisPoint;
const c0 = [shape.x, shape.y];
const c1 = [shape.x - offsetX, shape.y - offsetY];
const c2 = [xAxisPoint[0] - offsetX, xAxisPoint[1] - offsetY];
const c3 = [xAxisPoint[0], xAxisPoint[1]];
ctx.moveTo(c0[0], c0[1]).lineTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).closePath();
},
});
// 绘制右侧面
const CubeRight = echarts.graphic.extendShape({
shape: {
x: 0,
y: 0,
},
buildPath: function(ctx, shape) {
const xAxisPoint = shape.xAxisPoint;
const c1 = [shape.x, shape.y];
const c2 = [xAxisPoint[0], xAxisPoint[1]];
const c3 = [xAxisPoint[0] + offsetX, xAxisPoint[1] - offsetY];
const c4 = [shape.x + offsetX, shape.y - offsetY];
ctx.moveTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).lineTo(c4[0], c4[1]).closePath();
},
});
// 绘制顶面
const CubeTop = echarts.graphic.extendShape({
shape: {
x: 0,
y: 0,
},
buildPath: function(ctx, shape) {
const c1 = [shape.x, shape.y];
const c2 = [shape.x + offsetX, shape.y - offsetY]; //右点
const c3 = [shape.x, shape.y - offsetX];
const c4 = [shape.x - offsetX