最近寫一個項目要實現(xiàn)畫圖将饺,感覺ECharts這個框架里邊的圖效果好一點,所以就用這個插件來實現(xiàn)我得畫圖功能痛黎,我用的是折線圖予弧,想要畫柱狀圖、餅圖等湖饱,官網(wǎng)都有例子掖蛤,以下是我的實現(xiàn)步驟:
1、先用webStorm創(chuàng)建一個index.html井厌;
2坠七、直接進ECharts官網(wǎng):
(http://echarts.baidu.com/tutorial.html#5%20分鐘上手%20ECharts)
通過里邊給的幾種方式來獲取 ECharts,我用的是第一種方式直接下載旗笔,將下載下來的echarts.min.js拖入到index所在的文件夾彪置;
3、官網(wǎng)上邊有圖形使用的js的源代碼蝇恶,但是直接拿來用會報錯拳魁,以動態(tài)數(shù)據(jù)+時間坐標軸為例,官網(wǎng)的源代碼是:
function randomData() {
now = new Date(+now + oneDay);
value = value + Math.random() * 21 - 10;
return {
name: now.toString(),
value: [
[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
Math.round(value)
]
}
}
var data = [];
var now = +new Date(1997, 9, 3);
var oneDay = 24 * 3600 * 1000;
var value = Math.random() * 1000;
for (var i = 0; i < 1000; i++) {
data.push(randomData());
}
option = {
title: {
text: '動態(tài)數(shù)據(jù) + 時間坐標軸'
},
tooltip: {
trigger: 'axis',
formatter: function (params) {
params = params[0];
var date = new Date(params.name);
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1];
},
axisPointer: {
animation: false
}
},
xAxis: {
type: 'time',
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
boundaryGap: [0, '100%'],
splitLine: {
show: false
}
},
series: [{
name: '模擬數(shù)據(jù)',
type: 'line',
showSymbol: false,
hoverAnimation: false,
data: data
}]
};
setInterval(function () {
for (var i = 0; i < 5; i++) {
data.shift();
data.push(randomData());
}
myChart.setOption({
series: [{
data: data
}]
});
}, 1000);
以下是改之后可以直接復(fù)制到index.html運行的代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type='text/javascript' src='echarts.min.js' charset='utf-8'></script>
<title>charts</title>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于準備好的dom撮弧,初始化echarts實例
var myChart = echarts.init(document.getElementById('main'));//定義折線圖顯示的位置對象
function randomData() {
now = new Date(+now + oneDay);
value = value + Math.random() * 21 - 10;
return {
name: now.toString(),
value: [
[now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'),
Math.round(value)
]
}
}
var data = [];
var now = +new Date(1997, 9, 3);
var oneDay = 24 * 3600 * 1000;
var value = Math.random() * 1000;
for (var i = 0; i < 1000; i++) {
data.push(randomData());
}
option = {
title: {
text: '動態(tài)數(shù)據(jù) + 時間坐標軸'
},
tooltip: {
trigger: 'axis',
formatter: function (params) {
params = params[0];
var date = new Date(params.name);
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1];
},
axisPointer: {
animation: false
}
},
xAxis: {
type: 'time',
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
boundaryGap: [0, '100%'],
splitLine: {
show: false
}
},
series: [{
name: '模擬數(shù)據(jù)',
type: 'line',
showSymbol: false,
hoverAnimation: false,
data: data
}]
};
setInterval(function () {
for (var i = 0; i < 5; i++) {
data.shift();
data.push(randomData());
}
myChart.setOption(option);
}, 1000);
</script>
</body>
</html>
4潘懊、開始實現(xiàn)iOS跟html的交互,首先在iOS工程里邊創(chuàng)建WebView用來顯示html贿衍,要掛上代理UIWebViewDelegate
UIWebView *myWebView;
以下是UIWebView加載html頁面的代碼:
- (void)loadChat{
myWebView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.width, self.view.height)];
myWebView.scalesPageToFit = YES;
myWebView.delegate = self;
[self.view addSubview:myWebView];
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[myWebView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}
以下是UIWebView的代理方法:
//開始加載請求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
return YES;
}
//加載完成
- (void)webViewDidFinishLoad:(UIWebView *)webView{
}
注意在將html文件導(dǎo)入工程的時候要手動導(dǎo)入路徑授舟,不然會找不到路徑
5、在index.html里邊添加與ios交互的方法贸辈,代碼如下:
var ocValueData = [];
function setValueData(ocValue) {
console.log("ocValue"+ocValue);
for (var i = 0; i < ocValue.length; i++) {
ocValueData.push(randomData(ocValue[i],5));
}
myChart.setOption({
series: [{
data: ocValueData
}]
});
}
6释树、iOS傳數(shù)據(jù)到html頁面,我是用定時器生成隨機數(shù)直接傳到html頁面,代碼如下:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
sendDataArray = [NSMutableArray array];
[NSTimer scheduledTimerWithTimeInterval:0.15 target:self selector:@selector(action) userInfo:nil repeats:YES];
}
- (void)action{
sendDataArray = [NSMutableArray array];
for (int i = 0; i<9; i++) {
[sendDataArray addObject:@(arc4random()%2500+3000)];
}
NSLog(@"sendDataArray:%@",sendDataArray);
NSString *setValueData = [NSString stringWithFormat:@"setValueData([%@])",[sendDataArray componentsJoinedByString:@","]];
[myWebView stringByEvaluatingJavaScriptFromString:setValueData];
}
7奢啥、以下是html實現(xiàn)交互之后的所有代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type='text/javascript' src='echarts.min.js' charset='utf-8'></script>
<title>charts</title>
</head>
<body>
<div id="main" style="width: 100%;height:800px;"></div>
<!-- ECharts單文件引入 -->
<script type="text/javascript">
var ocValueData = [];
function setValueData(ocValue) {
console.log("ocValue"+ocValue);
for (var i = 0; i < ocValue.length; i++) {
if (ocValueData.length>600){
ocValueData.shift();
}
ocValueData.push(randomData(ocValue[i],5));
}
myChart.setOption({
series: [{
data: ocValueData
}]
});
}
var myChart = echarts.init(document.getElementById('main'));
function randomData(ocValue,time) {
now = new Date(+now +time);
value = ocValue;
return {
name: now.toString(),
value: [
now,
ocValue
]
}
}
var now = new Date();
var value = Math.random() * 1000;
var option = {
title: {
text: 'Realtime PPG'
},
textStyle:{
fontSize:30
},
tooltip: {
trigger: 'axis',
formatter: function (params) {
params = params[0];
var date = new Date(params.name);
return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + ' : ' + params.value[1];
},
axisPointer: {
animation: false
}
},
xAxis: {
type: 'time',
splitLine: {
show: false
}
},
yAxis: {
type: 'value',
boundaryGap: [0, '100%'],
splitLine: {
show: false
}
},
series: [{
name: '模擬數(shù)據(jù)',
type: 'line',
showSymbol: false,
hoverAnimation: false,
data: ocValueData
}
]
};
myChart.setOption(option);
</script>
</body>
</html>
了解:
ocValueData.shift():shift() 方法用于把數(shù)組的第一個元素從其中刪除秸仙,并返回第一個元素的值。如果數(shù)組是空的桩盲,那么 shift() 方法將不進行任何操作寂纪,返回 undefined 值。請注意赌结,該方法不創(chuàng)建新數(shù)組捞蛋,而是直接修改原有的 ocValueData;
ocValueData.length:數(shù)組ocValueData的元素個數(shù)柬姚;
ocValueData.push():push() 方法可向數(shù)組的末尾添加一個或多個元素襟交,并返回新的長度。push() 方法可把它的參數(shù)順序添加到 ocValueData 的尾部伤靠。它直接修改 ocValueData,而不是創(chuàng)建一個新的數(shù)組啼染。
設(shè)置x軸的時間間隔:通過更改randomData()方法里邊的time參數(shù)宴合,單位是毫秒,以上代碼時間間隔設(shè)置的是5毫秒,如果想顯示24小時的數(shù)據(jù)迹鹅,可以把now = new Date(+now +time)改成now = new Date();
setInterval(function () {
for (var i = 0; i < 5; i++) {
data.shift();
data.push(randomData());
}
myChart.setOption(option);
}, 1000);
這個方法是定時器卦洽,下邊的參數(shù)1000的單位是毫秒,也就是1秒產(chǎn)生5個隨機數(shù)
demo地址:https://github.com/chenmengdi/TestDemo
最后附上我的實現(xiàn)效果圖: