最近写一个项目要实现画图,感觉ECharts这个框架里边的图效果好一点,所以就用这个插件来实现我得画图功能,我用的是折线图,想要画柱状图、饼图等,官网都有例子,以下是我的实现步骤:
1、先用webStorm创建一个index.html;
2、直接进ECharts官网:
(http://echarts.baidu.com/tutorial.html#5%20分钟上手%20ECharts)
通过里边给的几种方式来获取 ECharts,我用的是第一种方式直接下载,将下载下来的echarts.min.js拖入到index所在的文件夹;
3、官网上边有图形使用的js的源代码,但是直接拿来用会报错,以动态数据+时间坐标轴为例,官网的源代码是:
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: '动态数据 + 时间坐标轴'
},
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: '模拟数据',
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);
以下是改之后可以直接复制到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: '动态数据 + 时间坐标轴'
},
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: '模拟数据',
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、开始实现iOS跟html的交互,首先在iOS工程里边创建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文件导入工程的时候要手动导入路径,不然会找不到路径
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传数据到html页面,我是用定时器生成随机数直接传到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实现交互之后的所有代码:
<!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: '模拟数据',
type: 'line',
showSymbol: false,
hoverAnimation: false,
data: ocValueData
}
]
};
myChart.setOption(option);
</script>
</body>
</html>
了解:
ocValueData.shift():shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。如果数组是空的,那么 shift() 方法将不进行任何操作,返回 undefined 值。请注意,该方法不创建新数组,而是直接修改原有的 ocValueData;
ocValueData.length:数组ocValueData的元素个数;
ocValueData.push():push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。push() 方法可把它的参数顺序添加到 ocValueData 的尾部。它直接修改 ocValueData,而不是创建一个新的数组。
设置x轴的时间间隔:通过更改randomData()方法里边的time参数,单位是毫秒,以上代码时间间隔设置的是5毫秒,如果想显示24小时的数据,可以把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);
这个方法是定时器,下边的参数1000的单位是毫秒,也就是1秒产生5个随机数
demo地址:https://github.com/chenmengdi/TestDemo
最后附上我的实现效果图: