Accelerometer value bar chart

We will put a canvas in each axis.

1<div class='row'>
2  <h2>X</h2>
3  <canvas id='x-canvas' width='80' height='40'></canvas>
4  <ul id='x' class='history'>
5    <li>No Data Yet</li>
6  </ul>
7</div>

We will use a graph to show the historical values of the sensor.

 1// Graph
 2;(function(){
 3  var app = this.app || (this.app={});
 4
 5  // A bar chart for - Max Value to + Max Value.
 6  app.Graph = (function(){
 7    function Graph(canvasId, maxValue){
 8      this.canvas = document.getElementById(canvasId);
 9      if (this.canvas) {
10        this.context = this.canvas.getContext('2d');
11      }
12
13      // set the Y unit scale.
14      this.unit = this.canvas.height / 2 / maxValue; // divide by 2 because half for + and half for -.
15    }
16    Graph.prototype.drawBar = function(x, value) {
17      var c = this.context;
18      c.beginPath();
19      c.moveTo(x, this.canvas.height/2); // middle
20      c.lineTo(x, this.canvas.height/2 - value * this.unit);
21      c.lineWidth = 3;
22      c.strokeStyle = "#222";
23      c.stroke();
24      c.closePath();
25    };
26    Graph.prototype.render = function(dataArray) {
27      this.canvas.width = this.canvas.width;
28      for (var i=0, len=dataArray.length; i<len; i++) {
29        this.drawBar(i*5, dataArray[i]);
30      }
31    }
32    return Graph;
33  })();
34}).call(this);

At last, we use the Graph to render the historical data.

1var graphX = new app.Graph('x-canvas', 2.5);
2graphX.render(app.xValues);

What’s next? We’re going to take a look at “Inspecting the gyroscope sensor”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content