优雅的制作一个温湿度计图表

1.有的和想要的

有数据:有温度、有湿度
想要的:显示在页面某个位置

2.期望的优雅

期望有一个方法,只需给定温度湿度位置,直接生成温湿度计图表。

3.来封装一个

3.1 先睹风采

使用以下方法即可完成图表显示。

Gauge.Hygrothermograph('gauge1', 28, 60);

效果如下:
温湿度计

3.2 使用方式

引入echart 和封装的 js ,即可使用 Gauge.Hygrothermograph 方法。

<script src="https://cdn.bootcss.com/echarts/4.2.1/echarts.min.js"></script>
<script src="http://www.timeddd.com/Demo/gauge.js"></script> 
3.3 完整的 html 如下:
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>仪表盘温湿度示例</title>    
<style>
    .gauge {
        width: 230px;
        height: 230px;
        border: solid 1px gray;
        padding: 5px;
    }
</style>
</head>
<body>
    <div id="gauge1" class="gauge"></div> 
    
    <script src="https://cdn.bootcss.com/echarts/4.2.1/echarts.min.js"></script>
    <script src="http://www.timeddd.com/Demo/gauge.js"></script>  
    <script>
        Gauge.Hygrothermograph('gauge1', 28, 60);
    </script>
        
</body>
</html>

3.3 封装思路

利用 echart 强大的图表功能,设置好适合温湿度呈现的 option,将数据部分参数化。为了支持更新时只修改 option 中的数据部分,定义一个列表来存储元素渲染过后的对象。

var Gauge = {}; 
Gauge.ChartList = {};

具体方法定义如下(option属性部分省略):

/**
 * 生成温湿计图表 
 * 
 *@param{string}elementId   显示温湿计表的HTML元素id
 *@param{number}temperature 温度
 *@param{number}humidity    湿度
 *@return 
*/
Gauge.Hygrothermograph = function(elementId, temperature, humidity){
    var ele = document.getElementById(elementId);
    var myChart = this.ChartList[elementId];   
    if(!myChart){        
        myChart = echarts.init(ele); 
        this.ChartList[elementId] = myChart;
    }else{ 
        var option = myChart.getOption();
        option.series[0].data[0].value = humidity;
        option.series[1].data[0].value = temperature;
        myChart.setOption(option, true); 
        return;
    }
    
    var option = {
       // .....
    };
    
    myChart.setOption(option, true);
}

完整代码请直接参数引用地址:
http://www.timeddd.com/Demo/gauge.js

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值