HTML Canvas 绘制实时动态折线图

    本文使用HTML的Canvas元素绘制实时动态折线图。

    参考于这篇博客HTML5 Canvas动画折线图 可动态添加节点

  1. 自定义Start、Stop按钮和画板canvas。
    <button id="start" style="text-align:center;">Start</button>
    <button id="stop" style="text-align:center;">Stop</button>
    <canvas id="canvas"></canvas>
  2.  定义start、stop、refresh的相关实现函数(注意这里需要引用相关库jquery-1.12.4.min.js和script.js)。1000为刷新间隔时间为1s,可自行修改刷新速度。这里有个知识点,js随机生成保留两位小数在100范围内的y_value值来更新折线。
    <script>
        var interval;
        var x_value=0;
        $(function(){
                $("#start").click(function(){
                    interval = setInterval(refresh,1000);
                });
            });
    
        function refresh(){
                var y_value = Math.round(Math.random()*100*100)/100;
                append(x_value,y_value);
                x_value = x_value + 1;
            }
        $(function(){
                $("#stop").click(function(){
                    clearInterval(interval);
                });
            });
      </script>
  3. 为了方便扩展,更改了原作者里面的append函数,用户可将x_value和y_value更改为自己需要刷新的数据。并将绘制画布更改为自己添加的canvas,添加更新Y轴坐标值。更改部分分别如下:
    function append(x_value,y_value) {
      chart.append([
        { label: x_value, value: y_value }
      ]);
    }
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext( '2d' );
    context.fillText( point.label, point.x - ( wordWidth / 2 ), height - 30 );
    context.fillText( point.value, 18, point.y);
  4. 执行Start可实时动态绘制折线图,执行Stop即可停止刷新。运行结果如下图所示:

猜你喜欢

转载自blog.csdn.net/qq_41672428/article/details/107453997