【问题标题】:Chartjs - pointColor to follow current color of gradient strokeChartjs - pointColor 跟随渐变笔划的当前颜色
【发布时间】:2015-08-08 17:07:10
【问题描述】:

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

接下来我需要的是让pointColor 跟随渐变stroke 并拾取它所在位置的当前颜色。喜欢这个photo

任何想法如何实现这一目标?

谢谢!

【问题讨论】:

  • 我最近写了关于如何创建渐变折线图的 Chart.js 教程blog.vanila.io/… .. 如果有人和我有同样的问题,它可能会很有用。 :)

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


【解决方案1】:

更新

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

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

  ...
  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/


【讨论】:

  • 非常感谢@potatopeelings! :) 那是完美的! :)
  • @Plavookac - 你知道吗。刚刚从这个答案 (stackoverflow.com/questions/33104231/…) 中意识到扩展是不必要的。我们只需要更改 pointColor : gradientstroke, pointStrokeColor : gradientstroke, 就可以了!
猜你喜欢
  • 2017-12-29
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多