2021SC@SDUSC
echarts如何实现图表绘制
例:用户使用echarts实现绘制折线图的代码
const echartsInstance = echarts.init(document.getElementById("main"))
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line'
}]
};
echartsInstance.setOption(option)
上述代码,使用echarts实现了简单的折线图绘制。echarts根据用户设定的option进行图表绘制。setOption()方法为用户使用echarts最直接的接口方法,用户通过setOption方法能够将设置好的option绑定至echarts图表中进行显示。
在echarts.js中,定义了我们使用echarts时直接调用的init、setOption等方法。
初始化echarts实例
在echarts.js文件中通过export init方法提供用户初始化echarts实例的接口,主要代码如下:
export function init(dom, theme, opts) {
if (__DEV__) {
// Check version
if ((zrender.version.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
throw new Error(
'zrender/src ' + zrender.version
+ ' is too old for ECharts ' + version
+ '. Current version need ZRender '
+ dependencies.zrender + '+'
);
}
if (!dom) {
throw new Error('Initialize failed: invalid dom.');
}
}
// 判断该DOM结构是否已经存在绑定的echarts实例
var existInstance = getInstanceByDom(dom);
if (existInstance) {
if (__DEV__) {
console.warn('There is a chart instance already initialized on the dom.');
}
return existInstance;
}
// 需要DOM结构设定特定的width以及height值
if (__DEV__) {
if (zrUtil.isDom(dom)
&& dom.nodeName.toUpperCase() !== 'CANVAS'
&& (
(!dom.clientWidth && (!opts || opts.width == null))
|| (!dom.clientHeight && (!opts || opts.height == null))
)
) {
console.warn('Can\'t get dom width or height');
}
}
// 新建Echarts实例
var chart = new ECharts(dom, theme, opts);
chart.id = 'ec_' + idBase++;
instances[chart.id] = chart;
modelUtil.setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
enableConnect(chart);
return chart;
}
Echarts对象
Echarts对象属性包括:
this._zr(Zrender实例)
this._dom(DOM)
this._theme(主题)
this._chartsViews&this._chartsMap(保存View数据)
this._componentsViews&this._componentsMap(保存component数据)
this._api(对外API数据)
this._model(该echarts实例信息)
…
Echarts对象方法包括:
getDom():获取当前实例所挂载的DOM信息
getZr():获取zrender实例
setOption():设置echarts option
setTheme():设置echarts主题
getModel():获取echarts实例
getOption():获取option信息
getWidth():this._zr.getWidth() => 通过zrender实例返回zrender中painter画布的大小
getHeight():同getWidth()
getRenderedCanvas():this._zr.painter.getRenderedCanvas() => 获取画布中渲染的canvas元素
dispatchAction(): 触发action
dispose():销毁echarts实例
…