Chartjs - pointColor跟随渐变笔划的当前颜色

时间:2015-08-08 17:07:11

标签: javascript charts chart.js linechart linear-gradients

我刚刚使用chartjs库创建了折线图,我设法用渐变色制作笔画。这是我到目前为止所做的简单fiddle示例。

接下来我需要的是让pointColor跟随渐变stroke并获取其位置的当前颜色。就像这个photo

任何想法如何实现?

谢谢!

1 个答案:

答案 0 :(得分:4)

<强>更新

来自Is it possible to add a drop shadow to chart.js line chart?的@AndyHolmes问题

不需要原始解决方案(扩展)。所需要的只是

  ...
  pointColor: gradientstroke
  ...

原始解决方案

只需延长线条并更新点颜色即可。您可以在绘图功能中执行此操作,但在初始化函数中执行此操作会很有效(启用动画时)

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

        var ctx = this.chart.ctx;
        // draw a line with the gradient, we use this to get each points color
        ctx.fillStyle = data.datasets[0].strokeColor;
        ctx.fillRect(0, 0, this.chart.width, 1);

        this.datasets.forEach(function (dataset) {
            dataset.points.forEach(function (point) {
                // get the color from the gradient drew above
                var imageData = ctx.getImageData(point.x, 0, 1, 1);
                var color = 'rgba(' + imageData.data[0] + ', ' + imageData.data[1] + ', ' + imageData.data[2] + ', ' + imageData.data[3] + ')';

                // the _saved is used by the tooltip refresh to draw the point when you mouseout
                point.fillColor = color;
                point._saved.fillColor = color;
                point.strokeColor = color;
                point._saved.strokeColor = color;
            })
        })

        // we need to call the render function again to overwrite what was drawn in the initialize render (otherwise we don't see the changed color when animation is false)
        // this also wipes out the reference gradient
        this.render();
    }
});

实际上不需要lineChartData中的pointColor和pointStrokeColor。请注意,如果您愿意,也可以以相同的方式覆盖pointHighlightStroke和pointHighlightFill。

你这样称呼它

new Chart(ctx).LineAlt(...

小提琴 - http://jsfiddle.net/w2nh153d/

enter image description here