gRaphael lineChart updating attempt
attempt at an updating graph (actually redraws it) uses knockout to monitor arrays and a timeout to add values to those arrays. When the second array gets its added value a knockout subscription calls the drawChart function which clears the raphael paper and creates a new linechart with the new values.
by kcar
HTML
<script src="http://blog.fruitsoftware.com/wp-content/raphaeljs/raphael-min.js"></script>
<script src="http://blog.fruitsoftware.com/wp-content/raphaeljs/g.raphael-min.js"></script>
<script src="http://blog.fruitsoftware.com/wp-content/raphaeljs/g.line-min.js"></script>
<script src="https://github.com/downloads/knockout/knockout/knockout-2.1.0.js"></script>
<div id="holder"></div>
CSS
#holder {
height: 600px;
width: 700px;
}
JavaScript
var r = {};
var x = [], y = [];
var xVals = ko.observableArray([1, 2, 3, 4, 5, 6, 7]);
var yVals = ko.observableArray([12, 32, 23, 15, 17, 27, 22]);
for (var i = 0; i < 1e6; i++) {
x[i] = i * 10;
y[i] = (y[i - 1] || 0) + (Math.random() * 7) - 3;
}
var lines = null;
var drawChart = function(){
if(r.clear){ //this clears the old paper and all the Raphael components it contains if it exists
r.clear();
}
var _xVals = [];
var _yVals = [];
_yVals[0] = [];
//checks to see if there are more than 30 values, if so it grabs just the most recent 30
//to keep the graph from getting too crowded
if(xVals().length > 30){
_.each(xVals(), function(value, index){
if(index > xVals().length -31) { _xVals.push(value); }
});
_.each(yVals(), function(value, index){
if( index > yVals().length -31) { _yVals[0].push(value); }
});
}else{
_xVals = xVals();
_yVals[0] = yVals();
}
r = Raphael("holder"),
txtattr = { font: "12px sans-serif" };
r.text(160, 10, "Symbols, axis and hover effect").attr(txtattr);
lines = r.linechart(10, 10, 300, 220, _xVals, _yVals, { nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: true })
.hoverColumn(function () {
this.tags = r.set();
for (var i = 0, ii = this.y.length; i < ii; i++) {
this.tags.push(r.tag(this.x, this.y[i], this.values[i], 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
}
}, function () {
this.tags && this.tags.remove();
});
lines.symbols.attr({ r: 3 }); //sets size of the dots
};
drawChart(); //draw the initial graph
//this subscription calls the anonfunct which calls drawChart/Debugging stuff every time the yArray changes
var subscription = yVals.subscribe(function(){
drawChart();
/* debugging stuff, uncomment out...