websocket+d3.JS实现图标实时更新

服务端代码:

//var connection=require('./config.js').connection;
//
//connection.connect();
//
//console.log('数据库连接成功');

var websocket=require('ws').Server;
var ws=new websocket({port:'8118'});
var dataset={
    "links": [
        {
            "bmmc": "办公厅",
            "value": 35
        },
        {
            "bmmc": "总编室",
            "value": 32
        },
        {
            "bmmc": "外事局",
            "value": 30
        },
        {
            "bmmc": "培训中心",
            "value": 29
        },
        {
            "bmmc": "纪检监察",
            "value": 28
        },
        {
            "bmmc": "总经理室",
            "value": 27
        },
        {
            "bmmc": "技术局",
            "value": 26
        },
        {
            "bmmc": "机关党委",
            "value": 25
        },
        {
            "bmmc": "人事局",
            "value": 24
        }
    ]
};


function randomInterval(min){
    var _num=Math.floor(Math.random()*20+min);
    if(_num>0){
        return Math.floor(Math.random()*20+min);
    }
}

function updataset(){
    var _index=Math.floor(Math.random()*8);
    var value=dataset.links[_index].value;
    dataset.links[_index].value=randomInterval(value-10)
}


ws.on('connection',function(wss){
 if(wss.readyState==1){
     setInterval(function(){
         updataset();
         wss.send(JSON.stringify(dataset));  //websocket支持的数据类型文本类型和二进制类型,所以要讲json格式转换为字符串,前台拿到数据后再通过json.parse转换
     },2000);
 }
});

ws.on('message',function(ws){
   console.log(ws);
});

客户端代码:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        body{
            background: black;
        }
        *{
            margin: 0;
            padding:0;
        }
        .y path,.y line,.x path,.x line{
            fill:none;
            stroke:black;
            stroke-width: .5;
        }
        .domain,.tick line,.y text{
            display: none;
        }

        text{
            fill: #fff;
            font-family: '微软雅黑';
        }
    </style>
</head>
<body>
<div id="chart" style="width: 1000px;height: 1000px">

</div>

<script type="text/javascript" src="js/d3.js"></script>
<script type="text/javascript" src="js/histogram.js"></script>
<script type="text/javascript">
  var ws = new WebSocket("ws://localhost:8118");
    ws.onopen=function(){
        NameSpace._startChart();
    };

    ws.onmessage=function(ws){
     var _data=JSON.parse(ws.data).links;
     NameSpace._drawChart(_data);
    }
</script>
</body>
</html>

histogram.js:

var NameSpace=window.NameSpace|| {
        width: 680,
        height: 500,
        margin: {left: 50, top: 30, right: 80, bottom: 20},
        delay: 50,
        rect: null,
        text: null,
        _color: ['#d22729', '#d25029', '#d27829', '#d29829', '#d2d128', '#a8d329', '#77d329', '#27d36d', '#27d3a1', '#27bcd4'],
        _startChart: function () {
            var _this = this;
            this.g_width = this.width - this.margin.left - this.margin.right;
            this.g_height = this.height - this.margin.top - this.margin.bottom;

            this.X = d3.scale.ordinal().rangeRoundBands([0, _this.g_height], .3);

            this.Y = d3.scale.linear()
                .range([this.g_width, 0]);

            this.aXis = d3.svg.axis().scale(this.X).ticks(10).orient('right');
            this.aYis = d3.svg.axis().scale(this.Y).orient('bottom');

            this.svg = d3.select('#chart')
                .append('svg')
                .attr('width', this.width)
                .attr('height', this.height);

            this.aXisg = this.svg.append('g')
                .attr('class', 'x')
                .attr('transform', 'translate(' + (this.width - this.margin.right) + ',' + (this.margin.top) + ')')


            this.aYisg = this.svg.append('g')
                .attr('class', 'y')
                .attr('transform', 'translate(' + (this.margin.left) + ',' + (this.g_height + this.margin.top) + ')');
        },
        _drawChart: function (data) {
            var _this = this;
            this.data = data;
            var maxvalue =d3.max(this.data,function(d){return d.value});
            this.X.domain(d3.map(this.data, function (d) {
                return d.bmmc
            }).keys());
            this.Y.domain([0, maxvalue + 5]);
            this.aXisg.call(_this.aXis);
            this.aYisg.call(_this.aYis);

            if (this.rect == null) {
                this.rect = this.svg.selectAll('rect')
                    .data(this.data)
                    .enter()
                    .append('rect')
                    .attr('transform', 'translate(' + (this.margin.left) + ',' + 0 + ')')
                    .attr('fill', function (d, i) {
                        return _this._color[i];
                    })
//                                .attr('x', function (d) {
//                                    return _this.g_width;
//                                })
//                                .attr('width', 0)
                    .attr("height", _this.X.rangeBand())
                    .attr('y', function (d) {
                        return _this.margin.top + _this.X(d.bmmc);
                    })
//                                .transition()
//                                .duration(1000)
//                                .delay(function (d, i) {
//                                    return i * _this.delay
//                                })
                    .attr('x', function (d) {
                        return _this.Y(d.value);
                    })
                    .attr('width', function (d) {
                        return _this.g_width - _this.Y(d.value);
                    });
//
                this.text = this.svg.selectAll('.texts')
                    .data(this.data)
                    .enter()
                    .append('text')
                    .attr('transform', 'translate(' + (this.margin.left) + ',' + 0 + ')')
//                                .attr('x', function (d) {
//                                    return _this.g_width - 30;
//                                })
                    .attr('y', function (d) {
                        return _this.margin.top + _this.X(d.bmmc) + (_this.X.rangeBand() / 2);
                    })
                    .attr('class', 'textvalue')
                    .text(function (d) {
                        return d.value
                    })
//                                .transition()
//                                .duration(1000)
//                                .delay(function (d, i) {
//                                    return i * _this.delay
//                                })
                    .attr('x', function (d) {
                        return _this.Y(d.value) - 30;
                    })

            }
            else {

                this.rect
                    .data(_this.data)
                    .transition()
                    .duration(1000)
                    .attr('x', function (d) {
                        return _this.Y(d.value);
                    })
                    .attr('width', function (d) {
                        return _this.g_width - _this.Y(d.value);
                    });
//
                this.text
                    .data(_this.data)
                    .text(function (d) {
                        return d.value
                    })
                    .transition()
                    .duration(1000)
                    .attr('x',function(d){
                        return _this.Y(d.value)-30;
                    })


            }
        }
    };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值