wjt
2024-07-23 c3b2d6d35b77d11ff86d45926501493b7fc8886e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<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>