这是我参与「第五届青训营」伴学笔记创作活动的第 6 天
ucharts柱形图的使用
用小程序开发的时候,遇到目标需求中有需要柱形图展示数据,我又不会canvas,所以就去寻找有没有插件或组件库,然后就找到这个uCharts跨平台图表库可以在uniapp中使用,其实还有ECharts,个人感觉这个更加出门点,但想着在uniapp中就用一下跟它有关系的,所以就来试试ucharts的柱形图组件
看看文档
最重要还是要先看文档,不要看得那么详细的某个组件的使用,比如我想使用组件形式,就重点看看组件相关的,这样也能比较快对组件的使用了解
看看效果
然后点顶部选项中的演示,选择目标图表,查看代码,不过就是要登录,有问题还可以在社区提问,不过!好像是第一次免费而已!我当时好像提问了一次,回答确实可以!
然后就是复制代码,看看能不能有一样的效果
接着,我们可以选择顶部选项中的文档去看,对应组件有哪些props,然后自己摸索一下改改一些东西
改改代码
当时可能涉及到组件复用,所以要监听数据变化重新渲染
小改onready函数
结合业务需求修改
接着就是手动更新图行以及监听点击事件
最最重要的部分就是画图的函数,记得把数据转成对应使用的格式
<script>
import uCharts from "@/uni_modules/qiun-data-charts/js_sdk/u-charts/u-charts.js";
var uChartsInstance = {};
export default {
methods: {
drawCharts(id, data) {
const query = uni.createSelectorQuery().in(this);
query
.select("#" + id)
.fields({ node: true, size: true })
.exec((res) => {
if (res[0]) {
const canvas = res[0].node;
const ctx = canvas.getContext("2d");
canvas.width = res[0].width * this.pixelRatio;//
canvas.height = res[0].height * this.pixelRatio;//
uChartsInstance[id] = new uCharts({
type: "column",
context: ctx,
width: this.cWidth * this.pixelRatio,//
height: this.cHeight * this.pixelRatio,//
categories: data.categories,//
series: data.series,//
pixelRatio: this.pixelRatio,
animation: true,
background: "#FFFFFF",
color: ["#86c882", "#008080"],
padding: [15, 15, 0, 5],
legend: {
show: false,
},
xAxis: {
disableGrid: true,
},
yAxis: {
data: [
{
min: 0,
max: this.ySplitNumber,//这个y轴高度就是动态计算
},
],
splitNumber: this.ySplitNumber / 5,
disableGrid: true,
},
extra: {
column: {
type: "group",
width: 40,
activeBgColor: "#000000",
activeBgOpacity: 0.08,
linearType: "custom",
// seriesGap: 5,
linearOpacity: 0.5,
barBorderCircle: true,
customColor: ["#6ed3d1"], //here,柱形图的颜色
barBorderRadius: [20, 20, 5, 5],
},
},
update: true,
});
} else {
console.error("[uCharts]: 未获取到 context");
}
});
},
},
};
</script>
使用时页面中这样简单引入
<process-histogram
canvasId="bCPwJJW"
:series="series"
:userType="2"
:listType="2"
></process-histogram>
当时做出来的效果图如下