# 柱状图

::: demo

<template>
  <canvas ref="bar"></canvas>
</template>

<script>
export default {
  data() {
    return {

    };
  },
  mounted() {
    var canvas = this.$refs.bar
    canvas.width = "600";
    canvas.height = "300";
    var ctx = canvas.getContext("2d");
    var x0 = 30, //x轴0处坐标
      y0 = 280, //y轴0处坐标
      x1 = 560, //x轴顶处坐标
      y1 = 30, //y轴顶处坐标
      dis = 30;

    draw();

    function draw() {
      //先绘制X和Y轴
      ctx.beginPath();
      ctx.lineWidth = 1;

      ctx.moveTo(x0, y1); //笔移动到Y轴的顶部
      ctx.lineTo(x0, y0); //绘制Y轴
      ctx.lineTo(x1, y0); //绘制X轴
      ctx.stroke();

      //绘制虚线和Y轴值
      var yDis = y0 - y1;
      var n = 1;
      ctx.fillText(0, x0 - 20, y0); //x,y轴原点显示0
      while (yDis > dis) {
        ctx.beginPath();
        //每隔30划一个虚线
        ctx.setLineDash([2, 2]); //实线和空白的比例
        ctx.moveTo(x1, y0 - dis);
        ctx.lineTo(x0, y0 - dis);
        ctx.fillText(dis, x0 - 20, y0 - dis);
        //每隔30划一个虚线
        dis += 30;
        ctx.stroke();
      }

      var xDis = 30, //设定柱子之前的间距
        width = 40; //设定每个柱子的宽度
      //绘制柱状和在顶部显示值
      for (var i = 0; i < 8; i++) {
        //假设有8个月
        ctx.beginPath();
        var color = "#" + Math.random().toString(16).substr(2, 6).toUpperCase(); //随机颜色
        ctx.fillStyle = color;
        ctx.font = "13px scans-serif"; //设置字体

        var height = Math.round(Math.random() * 220 + 20); //在一定范围内随机高度

        var rectX = x0 + (width + xDis) * i, //柱子的x位置
          rectY = height; //柱子的y位置

        ctx.fillText(i + 1 + "月份", rectX, y0 + 15); //绘制最下面的月份稳住

        ctx.fillRect(rectX, y0, width, -height); //绘制一个柱状

        ctx.fillText(rectY, rectX + 10, 280 - rectY - 5); //显示柱子的值
      }
    }
  },
};
</script>
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75

:::