# 常用教程
# 图表 ucharts
具体使用方法见 ucharts (opens new window)
案例:
<template>
<view >
<canvas canvas-id="hslysmyoqiqYsvLtEFkdZpaKqtlNTYTm"
id="hslysmyoqiqYsvLtEFkdZpaKqtlNTYTm" type="2d" class="charts" @touchend="tap" />
</view>
</template>
<script setup>
import { onReady } from '@dcloudio/uni-app';
import uCharts from '@qiun/ucharts';
import { reactive, getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const uChartsInstance = {};
const data = reactive({
cWidth: 750,
cHeight: 500,
pixelRatio: 2
});
const getServerData = () => {
//模拟从服务器获取数据时的延时
setTimeout(() => {
//模拟服务器返回数据,如果数据格式和标准格式不同,需自行按下面的格式拼接
const res = {
categories: ['2018', '2019', '2020', '2021', '2022', '2023'],
series: [
{
name: '成交量A',
data: [35, 8, 25, 37, 4, 20]
},
{
name: '成交量B',
data: [70, 40, 65, 100, 44, 68]
},
{
name: '成交量C',
data: [100, 80, 95, 150, 112, 132]
}
]
};
drawCharts('hslysmyoqiqYsvLtEFkdZpaKqtlNTYTm', res);
}, 500);
};
const drawCharts = (id, e) => {
//注:某些小程序不能使用2d,如支付宝小程序需另写实例方法
//小程序实例
// #ifdef MP-WEIXIN
const query = uni.createSelectorQuery().in(proxy);
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 * data.pixelRatio;
canvas.height = res[0].height * data.pixelRatio;
uChartsInstance[id] = new uCharts({
type: 'line',
context: ctx,
width: data.cWidth * data.pixelRatio,
height: data.cHeight * data.pixelRatio,
categories: e.categories,
series: e.series,
pixelRatio: data.pixelRatio,
animation: true,
background: '#FFFFFF',
color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE',
'#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
padding: [15, 10, 0, 15],
enableScroll: false,
legend: {},
xAxis: {
disableGrid: true
},
yAxis: {
gridType: 'dash',
dashLength: 2
},
extra: {
line: {
type: 'straight',
width: 2,
activeType: 'hollow'
}
}
});
} else {
console.error('[uCharts]: 未获取到 context');
}
});
// #endif
//其他平台实例
// #ifndef MP-WEIXIN
const ctx = uni.createCanvasContext(id);
uChartsInstance[id] = new uCharts({
type: "line",
context: ctx,
width: data.cWidth,
height: data.cHeight,
categories: e.categories,
series: e.series,
animation: true,
background: "#FFFFFF",
color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE",
"#3CA272","#FC8452","#9A60B4","#ea7ccc"],
padding: [15,10,0,15],
enableScroll: false,
legend: {},
xAxis: {
disableGrid: true
},
yAxis: {
gridType: "dash",
dashLength: 2
},
extra: {
line: {
type: "straight",
width: 2,
activeType: "hollow"
}
}
});
// #endif
};
const tap = (e) => {
uChartsInstance[e.target.id].touchLegend(e);
uChartsInstance[e.target.id].showToolTip(e);
};
onReady(() => {
// //这里的 750 对应 css .charts 的 width
data.cWidth = uni.upx2px(750);
// //这里的 500 对应 css .charts 的 height
data.cHeight = uni.upx2px(500);
data.pixelRatio = uni.getSystemInfoSync().pixelRatio;
getServerData();
});
</script>
<style scoped>
.charts {
width: 750rpx;
height: 500rpx;
}
</style>
← 通用方法