D3.js scrolling perf chart
by paulocoelho
HTML
<script src="http://d3js.org/d3.v2.min.js"></script>
<div id='testdiv' style="position:absolute; background-color:#eee; top:0px; left:0px; width:400px; height:300px"></div>
CSS
svg {
font: 10px sans-serif;
}
svg .svgPath {
stroke-width: 2;
stroke:#249bd5;
stroke-opacity: 0.7;
fill: #249bd5;
fill-opacity: 0.2;
}
svg .line {
fill: none;
stroke: #999;
stroke-width: 1px;
}
svg .line.dashed {
stroke-dasharray: 7 7;
}
svg .graphText {
font-size: 1em;
font-weight: bold;
fill:#999;
}
svg .line.red {
stroke:#ff7e81;
}
svg .redFill {
fill: #ff4c61;
}
svg .redLine{
stroke:#ff4c61;
}
JavaScript
var data = [100, 50, 0, 120, 110, 50, 0, 90, 10, 50, 0, 90, 10, 50, 0, 90, 10, 50, 0, 90, 10, 50, 0, 90, 10, 50, 0, 100];
var settings = ["100", "%"];
var x = new StarvingGraph('#testdiv', data, settings);
setInterval(function () {
x.push(Math.random() * 140);
}, 600);
function StarvingGraph(container, data, settings) {
var thisClass = this;
this.data = data;
this.data.unshift(0);
this.data.push(0);
this.settings = settings == undefined ? [15, ''] : settings;
this.container = container;
this.n = data.length;
this.duration = 600;
this.percentExtra = 0.4
this.width = $(container).width();
this.height = $(container).height();
this.graph = {
min: 0,
max: parseInt(this.settings[0] * (1 + this.percentExtra)), // the max of the graph will always be 40% more than the threshold
threshold: parseInt(this.settings[0]),
unit: this.settings[1]
}
// set X and Y scalers
this.x = d3.time.scale()
.domain([1, this.n - 2])
.range([-5, this.width]);
this.y = d3.scale.linear()
.domain([this.graph.min, this.graph.max])
.range([this.height, 0]);
// Define the line that goes over the graph
this.line = d3.svg.line() //.interpolate("basis")
.x(function (d, i) {
return thisClass.x(i);
})
.y(function (d, i) {
return thisClass.y(d);
});
// create the SVG inside the container
this.svg = d3.select(container).append("svg:svg")
.attr("width", this.width)
.attr("height", this.height);
// this part clips the TOP
this.svg.append("defs")
.append("clipPath")
.attr("id", "clipTOP")
.append("rect")
.attr("x", 0)
.attr("y", this.y(this.graph.threshold))
.attr("width", this.width)
.attr("height", this.y(0));
// this part clips the BOTTOM
this.svg.append("defs")
.append("clipPath")
.attr("id", "clipBOTTOM")
.append("rect")
.attr("x", 0)
.attr("y", this.y(this.graph.max))
.attr("width", this.width)
.attr("height",...