如何为chartjs栏中的每个栏设置全长背景颜色 [英] How to set a full length background color for each bar in chartjs bar

查看:13
本文介绍了如何为chartjs栏中的每个栏设置全长背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为chartjs bar中的每个bar设置全长背景色

请参考下面的链接我需要相同的输出

How to set a full length background color for each bar in chartjs bar

pls refer below link i need same output https://drive.google.com/file/d/0B4X0e4vwH_UPVGxWN2NBdURyZ0E/view?usp=sharing

解决方案

You can adapt the other answer to show the background only for the bars - note that in this case you'll need the bars collection

Chart.types.Bar.extend({
    name: "BarAlt",
    initialize: function (data) {
        var self = this;
        var originalBuildScale = self.buildScale;
        self.buildScale = function () {
            originalBuildScale.apply(this, arguments);

            var ctx = self.chart.ctx;
            var scale = self.scale;
            var originalScaleDraw = self.scale.draw;
            var barAreaWidth = scale.calculateX(1) - scale.calculateX(0);
            var barAreaHeight = scale.endPoint - scale.startPoint;

            self.scale.draw = function () {
                originalScaleDraw.call(this, arguments);
                ctx.fillStyle = data.barBackground;
                self.datasets.forEach(function (dataset) {
                    dataset.bars.forEach(function (bar) {
                        ctx.fillRect(
                            bar.x - bar.width / 2,
                            scale.startPoint,
                            bar.width,
                            barAreaHeight);
                    })
                })
                ctx.fill();
            }
        }

        Chart.types.Bar.prototype.initialize.apply(this, arguments);
    }
});

with the chart data like so

var data = {
    barBackground: "rgba(221, 224, 229, 1)",
    ...

and the call like so (as before)

var ctx = document.getElementById("chart").getContext("2d");
var myBarChart = new Chart(ctx).BarAlt(data, {
    barValueSpacing: 15,
});


Fiddle - http://jsfiddle.net/ayy2vxsj/


这篇关于如何为chartjs栏中的每个栏设置全长背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆