如何用canvas实现一个柱状图

首先我们得再body里写一个框


我们要获取我们这个盒子,并声明一个画布;

var c = document.getElementById('myCanvas')
    var cxt = c.getContext('2d');

接下来要画一个x轴和y轴然后进行位移

cxt.translate(200, 700)
    cxt.textAlign = 'center';//字体水平居中
    cxt.textBaseline = 'middle';//字体垂直居中
    //x轴
    cxt.beginPath();
    cxt.moveTo(0, 0);
    cxt.lineTo(500, 0);
    cxt.lineWidth = 3;
    cxt.strokeStyle = 'red'
    cxt.stroke()

    //y轴
    cxt.beginPath();
    cxt.moveTo(0, 0);
    cxt.lineTo(0, -650);
    cxt.strokeStyle = 'red'
    cxt.stroke()

渲染数据,把y轴的坐标给写入到页面里

   data = {
        x: ["一月", "二月", "三月", "四月", "五月", "六月"],
        y: ["0", "100", "200", "300", "400", "500", "600", "700", "800", "900", "1000"],
        val: ["300", "210", "120", "560", "800", "660"],
        col: ["red", "green", "blue", "skyblue", "limegreen", "pink"]
    }
    for (var i in data.y) {
        cxt.fillText(data.y[i], -40, -i * 60);
        cxt.beginPath();
        cxt.moveTo(0, -i * 60);
        cxt.lineTo(-8, -i * 60);
        cxt.lineWidth = 1;
        cxt.strokeStyle = 'red'
        cxt.stroke()
    }

渲染数据,把柱状图展示到页面

 for (var i = 0; i < data.val.length; i++) {
        cxt.beginPath();
        cxt.moveTo((i + 1) * 60, 0);
        cxt.lineTo((i + 1) * 60, -data.val[i] / 2);
        cxt.lineWidth = 40;
        cxt.strokeStyle = data.col[i];
        cxt.stroke()
        cxt.fillText(data.x[i], (i + 1) * 60, 20);
        cxt.fillText(data.val[i], (i + 1) * 60, -data.val[i] / 2 - 20);
    }

你可能感兴趣的:(如何用canvas实现一个柱状图)