最近在項目中用到了echarts,在處理視圖自適應問題上記錄一下;同時比較一下和highcharts的區別;
在echarts中有一個resize的函數,可以直接在監聽窗口變化時重新渲染即可;
//在原生代碼中 var myCharts = echarts.init(document.getElementById('#myCharts')) window.onresize = function (){ myCharts.resize() }
如果是在vue項目中用到(我的項目是vue框架)
//在vue中,將init的函數封裝在methods對象中,然后在該方法中調用resize函數 methods:{ initChart(){ this.chart = echarts.init(document.getElementById('chart')) let options = {}//省略 this.chart.setOption(options)
//resize的函數可在這里調用
window.onresize = function (){ this.chart.resize() } } }
在HighCharts中,有一個專門的函數可以直接設置。在highCharts的官方文檔中,有一個函數reflow()重新適應函數
reflow()讓圖表自適應容器,默認情況下,圖表會自動響應window.resize時間來自適應圖表容器(默認chart.reflow的配置是true),在圖表中沒辦法響應事件時,則需要手動調用該函數
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="pieContainer"></div>
<script src="js/highCharts/highcharts.js" type="text/javascript" charset="utf-8"></script>
<script src="js/highCharts/exporting.js" type="text/javascript" charset="utf-8"></script>
<script src="js/highCharts/highcharts-zh_CN.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var chart = Highcharts.chart('pieContainer', {
chart: {
spacing: [40, 0, 40, 0]
},
title: {
floating: true,
text: ' '
},
subtitle:{
text:'節點總數20個',
align:'center',
verticalAlign:'middle',
y:-10,
style:{
fontSize:14,
color:'#212121'
}
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
},
point: {
events: {
mouseOver: function(e) { // 鼠標滑過時動態更新標題
// 標題更新函數,API 地址:https://api.hcharts.cn/highcharts#Chart.setTitle
chart.setTitle({
text: e.target.name + '\t' + e.target.y + ' %'
});
}
//,
// click: function(e) { // 同樣的可以在點擊事件里處理
// chart.setTitle({
// text: e.point.name+ '\t'+ e.point.y + ' %'
// });
// }
}
},
events:{
mouseOut:function(e){
console.log(e)
$('tspan').html('節點總數20個')
}
}
}
},
series: [{
type: 'pie',
innerSize: '80%',
name: '市場份額',
data: [{
name: 'Firefox',
y: 45.0,
url: 'http://bbs.hcharts.cn'
},
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true,
url: 'http://www.hcharts.cn'
},
['Safari', 8.5],
['Opera', 6.2],
['其他', 0.7]
]
}]
}, function(c) { // 圖表初始化完畢后的會掉函數
// 環形圖圓心
var centerY = c.series[0].center[1],
titleHeight = parseInt(c.title.styles.fontSize);
// 動態設置標題位置
c.setTitle({
y: centerY + titleHeight / 2
});
});
</script>
</body>
</html>
