如何在Chart.js上自定义边框样式 [英] How to customize border style on Chart.js

查看:68
本文介绍了如何在Chart.js上自定义边框样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Chart.js上自定义边框样式

How to customize border style on Chart.js

Chart.js 2.2.1

默认情况下,条和点的边界是实线.如果可能的话,我想通过将边框变成虚线来引起对特定条形或线条的注意.

By default the border of bars and points is a solid line. If possible, I'd like to draw attention to specific bars or lines by making the border into a dotted or dashed line.

浏览文档没有发现任何有用的信息.以下是我认为可能有效的方法

Going through the docs didn't turn up anything useful. Below is what I thought might work

var ctx = document.getElementById("myChart");
var borderColors = ['red','blue','black']
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Black"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3],
            borderColor:borderColors,
            borderWidth:3,
            borderStyle:'dash'//has no effect
        }]
    }
});

这是实时运行.如何使边框变为虚线?

Here it is running live. How can I make a border dashed?

我的问题与这是一个类似的问题有两个原因

  1. 该解决方案将所有条形边框替换为虚线,而正如我所指出的,我只想设置数据集中特定条形的样式
  2. 该解决方案专用于条形图(它覆盖了 rectangle.draw 函数,而我提到我还想对数据集中的特定点(在折线图中)点划线
  1. that solution replaces all bar borders with dashed lines, whereas as I pointed out I'd like to style only specific bars within the dataset
  2. that solution is exclusively for bar charts (it overrides the rectangle.draw function whereas I mentioned that I'd like to also make point borders dashed (in line charts) for specific points within the dataset.

推荐答案

不是像

Instead of editing all the chart and the Rectangle as in the duplicate, you should do it only for each bar you want to display with dashed lines.

如果您看一看控制台(如果敢于深入研究对象,那么 console.log(myChart) 为您提供了很多信息),您将看到在 myChart.config.data.datasets [0] ._ meta [0] .data [ x ] x 是数据集的第x条.


知道应该去哪里后,您现在可以编辑 .draw()方法.

If you take a look at the console (console.log(myChart) provides you a lot of info if you dare go deep in the object), you will see that every bar is instancied in myChart.config.data.datasets[0]._meta[0].data[x], x being the xth bar of the dataset.


Knowing where you should go, you can now edit the .draw() method.

这是一个简单的函数,您可以使用它来使其工作:

Here is a simple function you can use to make it work :

function dashedBorder(chart, dataset, data, dash) {

    // edit the .draw() function
    chart.config.data.datasets[dataset]._meta[0].data[data].draw = function() {
        chart.chart.ctx.setLineDash(dash);
        Chart.elements.Rectangle.prototype.draw.apply(this, arguments);

        // put the line style back to the default value
        chart.chart.ctx.setLineDash([1,0]);
    }
}

您可以在此jsFiddle 中看到结果.

这篇关于如何在Chart.js上自定义边框样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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