快速上手
獲取 Apache ECharts
Apache ECharts 支援多種下載方式,我們將在下一篇教程下載和安裝中詳細介紹。這裡我們以從 jsDelivr CDN 獲取為例,講解如何快速安裝。
在 https://www.jsdelivr.com/package/npm/echarts 中選擇 dist/echarts.js
,點選並另存為 echarts.js
檔案。
有關這些檔案的更多資訊,請參閱下一篇教程下載和安裝。
引入 ECharts
在剛才儲存 echarts.js
的目錄中,新建一個 index.html
檔案,內容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!-- Include the ECharts file you just downloaded -->
<script src="echarts.js"></script>
</head>
</html>
開啟這個 index.html
時,你會看到一個空白的頁面。但別擔心,開啟控制檯,確保沒有報錯資訊,就可以進行下一步了。
繪製一個簡單的圖表
在繪製前,我們需要為 ECharts 準備一個定義了高寬的 DOM 容器。在剛才引入的 </head>
標籤後新增如下程式碼:
<body>
<!-- Prepare a DOM with a defined width and height for ECharts -->
<div id="main" style="width: 600px;height:400px;"></div>
</body>
然後你就可以透過 echarts.init 方法初始化一個 ECharts 例項,並透過 setOption 方法設定 ECharts 例項來生成一個簡單的柱狀圖。以下是完整程式碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ECharts</title>
<!-- Include the ECharts file you just downloaded -->
<script src="echarts.js"></script>
</head>
<body>
<!-- Prepare a DOM with a defined width and height for ECharts -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// Initialize the echarts instance based on the prepared dom
var myChart = echarts.init(document.getElementById('main'));
// Specify the configuration items and data for the chart
var option = {
title: {
text: 'ECharts Getting Started Example'
},
tooltip: {},
legend: {
data: ['sales']
},
xAxis: {
data: ['Shirts', 'Cardigans', 'Chiffons', 'Pants', 'Heels', 'Socks']
},
yAxis: {},
series: [
{
name: 'sales',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
// Display the chart using the configuration items and data just specified.
myChart.setOption(option);
</script>
</body>
</html>
這就是你用 Apache ECharts 實現的第一個圖表!