零、什么是Echarts
Echarts是谷歌的JavaScript开源库,主要用于实现网页端的图表操作。简单说就是,如果你需要在软件或网页内嵌一个交互式的折线图/饼图/柱状图,用Echarts就对了。
Echarts功能强大,具体参考官方文档:echarts官方API
这么好用的官方库,网上应该有很多教程吧?对,也不对。网上教程虽多,我上手这个库的时候还是走了不少弯路,遇到的问题很多,比如
1. 为什么已经执行legendSelect,依旧没有添加新曲线?
2. 为什么单击图例后图例变灰色表示取消选择,曲线没有同步取消选择?
...
这里先讲一下怎么调用echarts.js,再讲一下怎么解决图例与曲线不对应的问题。先上干货。
一、调用Echarts.js的方法
这里用比较简单的方法,就是下载echarts.min.js库。再在html文件中引用相应script
二、 怎样实现图例功能
首先在html文件中设置相应的代码块,比如这样
<body onresize="windowResize()">
<header>
<ul></ul>
</header>
<footer id="legend">
<div id="search"></div>
<ul></ul>
<div class="control-tools">
<a onclick="onLegendAllClick(true)">全选</a>
<a onclick="onLegendAllClick(false)">反选</a>
</div>
</footer>
<article id="chart"></article>
</body>
</html>
在上方代码中,我们定义了id为legend(汉文翻译为图例)的footer模块,后续就会在这个位置插入图例。 同理,id为search(搜索)的div模块后续会插入搜索框,id为chart的article模块会插入图表。注意,HTML文件只需要给出结构框架,确定不同组件的位置,至于组件的具体内容,是JavaScript代码要填充的,而组件的格式,是CSS代码确定的。
这也就是我们常提倡的模块化编程原理。不同的文件负责不同的功能,方便代码维护。
function updateLengend() {
// 图例 数据点列表
let legend = $("footer ul");
legend.empty();
let i = 0;
for (let item of selectedSeries) {
if (!item) continue;
let $radio = $("<li/>");
$radio.attr("style", `color: ${option.color[i % colorList.length]}`);
// 突出显示
let $icon = $("<a/>");
$icon.html(`<svg width="30" height="20" xmlns="http://www.w3.org/2000/svg">
<g>
<title>background</title>
<rect fill="none"/>
</g>
<g>
<path id="s2" stroke-width="2" stroke="${option.color[i % colorList.length]}" fill="#000" d="m2.7568,9.6l25,0"/>
<path id="s1" stroke-width="2" stroke="${option.color[i % colorList.length]}" fill="#fff" d="m20.8568,9.6a5.6,5.6 0 1 1 0,-0.0006"/>
</g>
</svg>`);
$icon.attr("onclick", `onLegendClick('${item}', false, this)`);
// 放大倍数
//$button = $("<button/>");
//$button.attr("value", "1");
//$button.attr("onclick", `onZoomClick(this)`);
// 数据点名称
let $label = $("<label></label>");
$label.text(item);
$label.attr("id", item);
$label.attr("onclick", `onLegendClick('${item}', true, this)`);
$radio.append($icon);
//$radio.append($button);
$radio.append($label);
legend.append($radio);
//alert("one Completed");
if (displaySeries.indexOf(item) == -1) {
chart.dispatchAction({
type: "legendUnSelect",
name: item,
})
if (!$label.hasClass("dismiss")) {
$label.addClass("dismiss");
}
}
else {
chart.dispatchAction({
type: "legendSelect",
name: item,
});
if ($label.hasClass("dismiss")) {
$label.removeClass("dismiss");
}
}
i++;
}
}
这个JavaScript代码里,我们把初始化图例的操作封装为一个函数。首先是提出HTML的footer块,命名为legend,再用clear方法清空legend的内容,然后在for循环中依次加入selectedSeries列表的内容。selectedSeries是全部图例,而displaySeries是选中的图例。如果某个系列的曲线是选中的图例,就执行chart.dispatchAction({type:"legendSelect",name:item})操作,即选中该图例。否则,取消选择该图例。
本人原先的代码没有在图例初始化就执行dispatchAction,导致后续的图例选择与曲线添加不同步。加入这一步之后,实现了同步。