2023-03-01 11:25

利用Chart绘制柱状图-显示柱状图数值

码自答

WEB前端

(819)

(0)

收藏

image.png

chart没有直接绘制数值,需要在canvas上添加绘制数值

获得chart在canvas上绘制得柱状图,在柱状图的正上方,通过fillText方法绘制数值

bar._model.x是绘制的柱状图的x坐标

bar._model.y是绘制的柱状图的y坐标

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
</head>
<body>
    <div style="width: 400px;height: 200px;">
   <canvas id="myChart"></canvas>
    </div>
</body>
<script> 
    var labels = ['一月','二月','三月','四月'];//标签
    var values = [230, 300, 530, 350];//数值
    var canvasId = "myChart";
    var title = "iphone14销量";//标题
    
    show(canvasId,labels,values,title);
    //绘制图形
    
 function show(canvasId,labels,values,title)
{        
        
        var data = {            
            labels: labels,//标签
            datasets: [{
                data: values, // 数值              
                label: title,// 标题
                backgroundColor: "rgb(255,100,150)",//颜色
                borderWidth: 1,//线粗细
            }]
        };
        
        var config = {
            type: 'bar',//图形类型
            data: data,
            options: {
                // 显示数值
                animation: {      
                    onComplete: function () {
                        var chartInstance = this.chart,

                        ctx = chartInstance.ctx;
                        // 以下属于canvas的属性(font、fillStyle、textAlign...)
                        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                        ctx.fillStyle = "black";
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'bottom';

                        this.data.datasets.forEach(function (dataset, i) {
                            var meta = chartInstance.controller.getDatasetMeta(i);
                            //meta.data柱状图得集合
                            meta.data.forEach(function (bar, index) {
                                var data = dataset.data[index];
                                ctx.fillText(data, bar._model.x, bar._model.y - 5);
                                //绘制数值
                            });
                        });
                    }
                }
            }
        };
    
        // 绘制图表
        var ctx = document.getElementById(canvasId);
        var bar = new Chart(ctx, config);
}
</script>
</html>


0条评论

点击登录参与评论