外掛介紹
外掛是開發人員在建立圖表時修改圖表的一種方式。Chart.js 呼叫以下圖表狀態的所有外掛:
- 開始初始化
- 初始化結束
- 更新開始
- 圖表比例計算完畢後
- 開始更新資料集
- 資料集更新結束
- 更新結束(渲染髮生之前)
- 開始抽獎
- 抽籤結束
- 在資料集繪製之前
- 資料集繪製後
- 調整
- 在動畫開始之前
建立一個外掛
要建立外掛,請為要修改的任何圖表狀態(上面列出)建立具有適當命名函式的 JavaScript 物件。獲得外掛物件後,將其傳遞給 Chart.pluginService.register(PLUGIN_OBJECT_NAME);
,讓 Chart.js 知道註冊外掛。
最小外掛示例
// Create the plugin object with functions for all the chart states
var simplePlugin = {
beforeInit: function(chartInstance) {},
afterInit: function(chartInstance) {},
resize: function(chartInstance, newChartSize) {},
beforeUpdate: function(chartInstance) {},
afterScaleUpdate: function(chartInstance) {},
beforeDatasetsUpdate: function(chartInstance) {},
afterDatasetsUpdate: function(chartInstance) {},
afterUpdate: function(chartInstance) {},
// This is called at the start of a render. It is only called once, even if the animation will run for a number of frames. Use beforeDraw or afterDraw
// to do something on each animation frame
beforeRender: function(chartInstance) {},
// Easing is for animation
beforeDraw: function(chartInstance, easing) {},
afterDraw: function(chartInstance, easing) {},
// Before the datasets are drawn but after scales are drawn
beforeDatasetsDraw: function(chartInstance, easing) {},
afterDatasetsDraw: function(chartInstance, easing) {},
destroy: function(chartInstance) {}
};
// Let Chart.js know about the new plugin
Chart.pluginService.register(simplePlugin);
目前這個最小的外掛沒有做任何事情。要使此外掛有用,需要將程式碼新增到修改圖表的函式中。