快速上手
获取 Apache ECharts
Apache ECharts 支持多种安装方式,在接下来的安装教程中有详细介绍。这里,我们以使用 jsDelivr CDN 为例,快速搭建 ECharts 环境。
在 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 方法来配置它以生成一个简单的柱状图。这里是完整的代码。
<!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 and the data defined above.
myChart.setOption(option);
</script>
</body>
</html>这样,你就用 Apache ECharts 绘制出了你的第一个图表!