uniapp绘制曲线图
使用 uCharts 绘制曲线图
uCharts 是专为 UniApp 设计的高性能图表库,支持多种图表类型,包括曲线图。安装 uCharts 后,在项目中引入并配置即可使用。
在 pages 目录下的页面文件中,通过以下代码实现曲线图绘制:
<template>
<view>
<qiun-data-charts type="line" :chartData="chartData" />
</view>
</template>
<script>
export default {
data() {
return {
chartData: {
categories: ["1月", "2月", "3月", "4月", "5月", "6月"],
series: [
{
name: "销量",
data: [35, 28, 45, 60, 75, 90]
}
]
}
};
}
};
</script>
使用 ECharts 适配方案
通过 echarts-for-wx 或 mpvue-echarts 等适配库,可以在 UniApp 中使用 ECharts 绘制曲线图。需要先安装 ECharts 核心库和适配器。
在页面中引入 ECharts 并初始化图表:
<template>
<view>
<ec-canvas id="chart" canvas-id="chart" ec="{{ ec }}"></ec-canvas>
</view>
</template>
<script>
import * as echarts from 'echarts';
import ecCanvas from '@/components/ec-canvas/ec-canvas';
export default {
components: { ecCanvas },
data() {
return {
ec: {
lazyLoad: true
}
};
},
onReady() {
this.initChart();
},
methods: {
initChart() {
const chart = echarts.init(document.getElementById('chart'));
chart.setOption({
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
});
}
}
};
</script>
使用 F2 移动端图表库
F2 是蚂蚁金服推出的移动端可视化解决方案,适合在 UniApp 中绘制轻量级曲线图。需要安装 @antv/f2 并通过 Canvas 渲染。
在页面中配置 F2 图表:
<template>
<view>
<canvas canvas-id="f2-canvas" id="f2-canvas"></canvas>
</view>
</template>
<script>
import F2 from '@antv/f2';
export default {
onReady() {
const data = [
{ month: 'Jan', value: 35 },
{ month: 'Feb', value: 28 },
{ month: 'Mar', value: 45 }
];
const chart = new F2.Chart({
id: 'f2-canvas',
pixelRatio: window.devicePixelRatio
});
chart.source(data);
chart.line().position('month*value');
chart.render();
}
};
</script>
自定义 Canvas 绘制
对于简单需求,可直接使用 UniApp 的 Canvas API 手动绘制曲线。通过计算坐标点和贝塞尔曲线实现基本曲线图。
示例代码结构:
<template>
<view>
<canvas canvas-id="myCanvas" style="width:300px;height:200px;"></canvas>
</view>
</template>
<script>
export default {
onReady() {
const ctx = uni.createCanvasContext('myCanvas');
ctx.moveTo(0, 100);
ctx.bezierCurveTo(75, 50, 150, 150, 300, 100);
ctx.stroke();
ctx.draw();
}
};
</script>
性能优化建议
- 大数据量时启用图表的分段渲染或降采样功能
- 避免频繁更新图表数据,使用防抖机制控制刷新频率
- 对于静态图表,可将渲染结果保存为图片缓存
- 使用 web-view 嵌入图表时注意跨平台兼容性
以上方案根据项目需求和复杂度选择,uCharts 为原生支持方案,ECharts 适合复杂可视化,F2 侧重移动端性能,Canvas 适合定制化需求。






