基礎概念
- 使用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設置(當鼠標經過某個區域時的)