如何使用纯JavaScript创建动画图表(移动情节)?

时间:2016-06-13 04:13:14

标签: javascript animation canvas plot charts

我需要使用移动相机创建动画图表而不使用任何jquery插件。我需要从头开始编写代码,我只能使用jquery,没有插件。

我设法编写了绘制图表的代码。唯一的问题是如何与图表同时移动视口(相机)?

我知道我需要使用translate方法。但我不知道如何正确使用它。

我需要创建的图表理念:

example of chart

链接到codepen: http://codepen.io/sigmaray/pen/EyKNmK

我的代码:

$(function() {
  // Settings
  CAN_WIDTH = 300;
  CAN_HEIGHT = 300;
  CAN_COLOR = "#ccc";
  LINE_HEIGHT = 1;
  INTERVAL = 50;
  $DIV = $("#container");

  lineX = 0;
  lineY = CAN_HEIGHT / 2;
  ctx = null;

  randomNum = function(max, min) {
    if (min == null) {
      min = 0;
    }
    return Math.floor(Math.random() * (max - min) + min);
  };

  createCanvas = function() {
    canvas = document.createElement('canvas');
    canvas.width = CAN_WIDTH;
    canvas.height = CAN_HEIGHT;
    ctx = canvas.getContext('2d');
    $DIV.append(canvas);
  };

  timerAnimation = function(callback) {
    window.setTimeout(callback, INTERVAL);
  };

  anim = function() {
    if (lineX > CAN_WIDTH) {
      lineX = 0;
    }
    if (lineX === 0) {
      ctx.fillStyle = CAN_COLOR;
      ctx.fillRect(0, 0, CAN_WIDTH, CAN_HEIGHT);
    }
    oldLineX = lineX;
    oldLineY = lineY;
    lineY = randomNum(CAN_HEIGHT * (2 / 3), CAN_HEIGHT / 3);
    xOffset = randomNum(10, 1);
    lineX += xOffset;
    ctx.beginPath();
    ctx.lineWidth = LINE_HEIGHT;
    ctx.moveTo(oldLineX, oldLineY);
    ctx.lineTo(lineX, lineY);
    ctx.stroke();

    // !!! Doesn't work as expected !!!
    // ctx.translate(xOffset, 0)
    // ctx.save();
  };

  drawingCycle = function() {
    anim();
    timerAnimation(drawingCycle);
  };

  createCanvas();
  drawingCycle();
});

0 个答案:

没有答案