如何绘制使用HTML画布绘制的动态图表的X轴和y轴

时间:2016-08-21 09:14:48

标签: javascript html html5 canvas

我想为使用CANVAS html元素创建的动态图表绘制x轴和y轴。图表包含一条移动线,表示属性x和y表示x和y坐标的对象集。这些值的值应在x轴和y轴上描绘点。 x轴和y轴必须描绘移动线上的点的x和y坐标。我的代码的Plunker是:https://plnkr.co/edit/zo2dmHTzjywMnt5NIWUT?p=preview

我目前的代码是:



<html>

<head>
  <style type="text/css">
    #wave {
      background: #AAA;
    }
  </style>
</head>

<body>
  <canvas id="wave"></canvas>
  <script type="text/javascript">
    var dataArray = [{
      x: 0,
      y: 0
    }, {
      x: 1,
      y: 10
    }, {
      x: 2,
      y: 13
    }, {
      x: 3,
      y: 18
    }, {
      x: 4,
      y: 20
    }, {
      x: 5,
      y: 17
    }, {
      x: 6,
      y: 10
    }, {
      x: 7,
      y: 13
    }, {
      x: 8,
      y: 18
    }, {
      x: 9,
      y: 20
    }, {
      x: 10,
      y: 17
    }, {
      x: 11,
      y: 13
    }, {
      x: 12,
      y: 18
    }, {
      x: 13,
      y: 20
    }, {
      x: 14,
      y: 17
    }, {
      x: 15,
      y: 10
    }, {
      x: 16,
      y: 13
    }, {
      x: 17,
      y: 18
    }, {
      x: 18,
      y: 20
    }, {
      x: 19,
      y: 100
    }];
    (function() {
      var canvas = document.getElementById("wave");
      canvas.style.width = "500px";
      canvas.style.height = "100px";

      //High dpi stuff
      canvas.width = parseInt(canvas.style.width) * 2;
      canvas.height = parseInt(canvas.style.height) * 2;

      //Get canvas context
      var ctx = canvas.getContext("2d");

      //Stroke color
      ctx.strokeStyle = "#ffff00";

      //Draw thicker lines due to high dpi scaling
      ctx.lineWidth = 2;
      var dps = [];
      for (var a = 0; a < 20; a++) {
        dps[a] = dataArray[a];
      }
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      for (var b = 0; b < 19; b++) {
        var x1 = (canvas.width * b) / 19;
        var x2 = (canvas.width * (b + 1)) / 19;
        ctx.beginPath();
        ctx.moveTo(x1, (1 - (dps[b].y / 100)) * canvas.height);
        ctx.lineTo(x2, (1 - (dps[b + 1].y / 100)) * canvas.height);
        ctx.stroke();
      }
      interval = setInterval(function() {
        updateChart()
      }, 1000);
      c = 0;

      function updateChart() {
        if (c < 50) {
          dps.push({
            x: c,
            y: Math.round(Math.random() * 100)
          });
          c++;
          if (dps.length > 19) {
            dps.shift();
          }
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          for (var b = 0; b < 19; b++) {
            var x1 = (canvas.width * b) / 19;
            var x2 = (canvas.width * (b + 1)) / 19;
            ctx.beginPath();
            ctx.moveTo(x1, (1 - (dps[b].y / 100)) * canvas.height);
            ctx.lineTo(x2, (1 - (dps[b + 1].y / 100)) * canvas.height);
            ctx.stroke();
          }
        }

      }

    })();
  </script>
</body>

</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案