Jump To …

plot.js

/*global trurl*/

(function (global) {

var plot = function (id, width, height) {
  var canvas, 
    context,
    clearRectY, 
    clipValue = 0.8,
    event,
    that = {};

  trurl.util.eventify(that);
  event = that.event;

  width = width || 500;
  height = height || 500;

  if (!(!!document.createElement('canvas').getContext)) {
    return;
  }

  function init () {
    var scaleY;

    canvas = document.createElement('canvas');
    if (id) { canvas.id = id; }
    canvas.width = width;
    canvas.height = height;  
    canvas.style.background = '#ffffff';  

    scaleY = Math.floor(height/2);
    context = canvas.getContext('2d');
    context.translate(0, height/2);
    context.transform(1, 0, 0, -scaleY, 0, 0, 0, 0);
    context.lineWidth = 1/scaleY;

    clearRectY = -Math.floor(height/2);

    return canvas;
  }

  function setSize (w, h) {
    width = w;
    height = h;
  }

  function draw (data, data2) {
    var dataLength,
      i,
      samplesPerPixel, timeIt;

    timeIt = new Date().getTime();

    if (data2) { dataLength = data.length; }
    else { dataLength = data.length / 2; }
    samplesPerPixel = Math.floor(dataLength/width);

    context.clearRect(0, clearRectY, width, height);
    context.strokeStyle = '#ff0000'; 
    context.beginPath();
    context.moveTo(0,0);

    if (data2) {
      for (i=0; i<dataLength; i+=samplesPerPixel) {
        context.lineTo(i/samplesPerPixel+1, data[i] + data2[i]);
      }
    } else {
      for (i=0; i<dataLength; i+=samplesPerPixel) {
        context.lineTo(i/samplesPerPixel+1, data[i*2] + data[i*2+1]);
      }
    }

    context.stroke();

    timeIt = new Date().getTime() - timeIt;
    event('waveformDone', { time: timeIt }); 
  }


  that.init = init;
  that.setSize = setSize;
  that.draw = draw;

  return that;
};

if (typeof module != 'undefined' && module.exports) {
  module.exports = plot;
} else {
  global.trurl = global.trurl || {};
  global.trurl.plot = plot;
}

}(this));