<template>
|
<view>
|
<canvas canvas-id="bar-chart" style="width: 300px; height: 200px;"></canvas>
|
</view>
|
</template>
|
|
<script>
|
export default {
|
data() {
|
return {
|
data: [50, 120, 200, 150, 50], // 示例数据
|
barWidth: 20, // 条形的宽度
|
barGap: 5, // 条形之间的间隔
|
maxData: 200, // 数据的最大值,用于Y轴刻度
|
};
|
},
|
mounted() {
|
this.drawBarChart();
|
},
|
methods: {
|
drawBarChart() {
|
const ctx = uni.createCanvasContext('bar-chart', this);
|
const canvasWidth = 300;
|
const canvasHeight = 200;
|
const xScale = this.barWidth + this.barGap; // x轴的比例
|
const yScale = canvasHeight / this.maxData; // y轴的比例
|
|
// 绘制背景
|
ctx.fillStyle = '#f3f3f3';
|
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
|
|
// 绘制边框
|
ctx.strokeStyle = '#000';
|
ctx.setLineWidth(1);
|
for (let i = 0; i < this.data.length; i++) {
|
const x = i * xScale;
|
const y = canvasHeight - this.data[i] * yScale;
|
const width = this.barWidth;
|
const height = this.data[i] * yScale;
|
|
// 绘制条形
|
ctx.setFillStyle('#1890ff');
|
ctx.fillRect(x, y, width, height);
|
|
// 绘制边框
|
ctx.strokeRect(x, y, width, height);
|
|
// 可以添加数据标签
|
ctx.fillStyle = '#000';
|
ctx.font = '12px Arial';
|
ctx.fillText(this.data[i], x, y - 10);
|
}
|
|
ctx.draw();
|
}
|
}
|
};
|
</script>
|