Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine

I would like to try and create a radar chart using Chart.js which has various colours for each scaleLine, or coloured between the scaleLines. I was wondering if this was possible?

From:

enter image description here

To:

enter image description here

I currently have a working graph, though there doesn't seem to be a method to change individual scale lines.

Kind Regards Leigh

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can extend the radar chart type to do this, like so

Chart.types.Radar.extend({
    name: "RadarAlt",
    initialize: function (data) {
        Chart.types.Radar.prototype.initialize.apply(this, arguments);

        var originalScaleDraw = this.scale.draw;
        var ctx = this.chart.ctx;
        this.scale.draw = function () {
            var lineWidth = this.lineWidth;
            // this bypasses the line drawing in originalScaleDraw
            this.lineWidth = lineWidth;

            originalScaleDraw.apply(this, arguments);

            ctx.lineWidth = this.lineWidth;
            var scale = this;
            // now we draw
            Chart.helpers.each(scale.yLabels, function (label, index) {
                // color of each radial line - you could replace this by an array lookup (if you limit your scaleSteps)
                ctx.strokeStyle = "hsl(" + index / scale.yLabels.length * 360 + ", 80%, 70%)";

                // copy of the chart.js code
                ctx.beginPath();
                for (var i = 0; i < scale.valuesCount; i++) {
                    pointPosition = scale.getPointPosition(i, scale.calculateCenterOffset(scale.min + (index * scale.stepValue)));
                    if (i === 0) {
                        ctx.moveTo(pointPosition.x, pointPosition.y);
                    } else {
                        ctx.lineTo(pointPosition.x, pointPosition.y);
                    }
                }
                ctx.closePath();
                ctx.stroke();
            });
        }
    }
});

and then call it like so

var ctx = document.getElementById("myChart").getContext("2d");
var myRadarChart = new Chart(ctx).RadarAlt(data, {
    scaleLineWidth: 10
});

// this is requried if you have animation: false
// myRadarChart.update();

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


Of course, the sane thing would be to change the lightness value instead of the hue value :-)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...