是否可以使用runtime
在javascript
更改图表主题?我无法在任何地方找到这样做的例子。
我尝试使用validateNow
但没有成功。
谢谢!
如果要在运行时更改主题,则必须使用clear
方法清除图表实例并重新创建图表。
这是一个例子:
var chart;
var chartConfig = {
type: "serial",
dataProvider: [{
"year": 2005,
"income": 23.5,
"expenses": 18.1
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8
}, {
"year": 2007,
"income": 30.1,
"expenses": 23.9
}, {
"year": 2008,
"income": 29.5,
"expenses": 25.1
}, {
"year": 2009,
"income": 24.6,
"expenses": 25
}],
categoryField: "year",
categoryAxis: {
gridPosition: "start"
},
valueAxes: [{
title: "Million USD"
}],
graphs: [{
type: "column",
title: "Income",
valueField: "income",
lineAlpha: 0,
fillAlphas: 0.8,
balloonText: "[[title]] in [[category]]:<b>[[value]]</b>"
}, {
type: "line",
title: "Expenses",
valueField: "expenses",
lineThickness: 2,
bullet: "round",
balloonText: "[[title]] in [[category]]:<b>[[value]]</b>"
}],
legend: {
useGraphSettings: true
}
};
function createChart(theme) {
if (chart && chart.clear) {
chart.clear();
}
var config = JSON.parse(JSON.stringify(chartConfig)); //clone the config before reusing it
config.theme = theme;
if (theme === "dark") {
document.body.style.backgroundColor = "#282828";
}
else {
document.body.style.backgroundColor = "#ffffff";
}
chart = AmCharts.makeChart("chartdiv", config);
}
//set up event handler for switching themes
Array.prototype.forEach.call(
document.querySelectorAll("#theme-switch li"),
function (li) {
li.addEventListener("click", function() {
createChart(li.id);
});
}
);
createChart("none");
#theme-switch li {
display: inline;
width: 10%;
padding: 0 2em;
border: 1px solid #ccc;
color: #0000ff;
cursor: pointer;
background-color: #ececec;
}
#chartdiv {
width: 100%;
height: 400px;
}
<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/serial.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/themes/none.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/themes/light.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/themes/dark.js"></script>
<ul id="theme-switch">
<li id="none">None</li>
<li id="light">Light</li>
<li id="dark">Dark</li>
</ul>
<div id="chartdiv">
</div>