chartjs 初步

基础概念

  • 使用chartjs之前需要在HTML文档中定义一个画布:<canvas id="myChart" width="400" height="400"></canvas>
  • 然后使用chartjs来控制mychart的显示
    * 第一步要获得canvas的DOM:var ctx = document.getElementById("myChart").getContext("2d");chartjs提供几种方式来获得mychart元素,但比较可靠的是当前方法
    * 画图:
```
var chartInstance = new Chart(
ctx, //第一个参数是从HTML中获得的元素(上面第一步获得的变量 ctx)
{//第二个参数包含了图像的设置,如图形的形式:线图,饼图...;要显示的数据data,;其他如字体等
    type: 'line',
    data: data,
    options: {
        responsive: false
    }
});
```
  • chartjs可以使用全局的配置也可以分别为chart提供配置。

常用设置

  • 适用于所有chart的选项(这里只列出了一部分)
    * events ,类型 array[string],默认 ["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"],chart的提示与hovering所监听的事件。
    * onClick,类型:function;默认null;
    * legendCallback,类型:function;默认:function (chart)
  • 标题设置(将设置写进aptions.title中)
名称             类型           默认值      说明
display          Boolean        false    Display the title block
position         String           'top'    Position of the title. Only 'top' or 'bottom' are currently allowed
fullWidth       Boolean        true    Marks that this box should take the full width of the canvas (pushing down other boxes)
fontSize        Number       12    Font size inherited from global configuration
fontFamily    String           "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"    Font family inherited from global configuration
fontColor      Color            "#666"    Font color inherited from global configuration
fontStyle       String           'bold'    Font styling of the title.
padding        Number        10    Number of pixels to add above and below the title text
text                String            ''     Title text
//举例
var chartInstance = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        title: {
            display: true,
            text: 'Custom Chart Title'
        }
    }
})
  • 图例设置(与matlab中的legend意义相同,设置位于options.legend中)
//示例
var chartInstance = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        legend: {
            display: true,
            labels: {
                fontColor: 'rgb(255, 99, 132)'
            }
        }
    }
});
  • 提示设置 Tooltip(鼠标指向某点时显示提示)
  • hover设置(当鼠标经过某个区域时的)
posted @ 2016-07-23 16:43  jiahu  阅读(2668)  评论(0编辑  收藏  举报