Skip to content

Instantly share code, notes, and snippets.

@banderson623
Created April 5, 2013 22:49
Show Gist options
  • Save banderson623/5323311 to your computer and use it in GitHub Desktop.
Save banderson623/5323311 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Plotting Test</title>
<style>
canvas { border:1px solid black;}
</style>
</head>
<body>
<canvas id="sample" width="600" height="300"></canvas>
<p>fps: <span id="fps">0</span></p>
<p>If the fps value is changing like wild, it is probably struggling to get the desired frames per second</p>
</body>
<script>
var RemotePlot = {
canvas: null,
ctx: null,
data: [],
dataSize: 10000,
plotWidth: 0,
fpsElement: null,
// ---- Change this for testing ----------------------------------
desiredFPS: 60,
// ---------------------------------------------------------------
initialize: function(){
this.canvas = document.getElementById('sample');
this.fpsElement = document.getElementById('fps');
this.ctx = this.canvas.getContext('2d');
this.plotWidth = this.canvas.width;
this.loadData();
this.updatePlot();
setInterval(RemotePlot.updatePlot, 1000/this.desiredFPS);
this.startTime = new Date().getMilliseconds();
},
loadData: function(){
var variation = 10;
var lastDataPoint = Math.random() * 10;
for(var i = 0; i < this.dataSize; i++){
var delta = ((Math.random() - 0.5)*variation);
var lastDataPoint = Math.abs(lastDataPoint + delta);
this.data[i] = lastDataPoint;
}
},
wiggleData:function(){
var variation = 2;
for(var i = 0; i < RemotePlot.data.length; i++){
var delta = ((Math.random() - 0.5)*variation);
RemotePlot.data[i] = Math.abs(RemotePlot.data[i] + delta);
}
},
clearPlot: function(){
this.ctx.clearRect(0, 0, this.canvas.width,
this.canvas.height);
},
updatePlot: function(){
RemotePlot.wiggleData();
var yStart = RemotePlot.data[0]+10;
var yScaledValue;
// x value scale
var xScaleFactor = RemotePlot.plotWidth/RemotePlot.data.length;
var yScaleFactor = 10;
// Clear the plot and get it ready for the next line
RemotePlot.clearPlot();
// Get to the correct data place
RemotePlot.ctx.moveTo(0,yStart);
// Place pen down
RemotePlot.ctx.beginPath();
// Plot the data
for(var i = 0; i < RemotePlot.data.length; i++){
yScaledValue = RemotePlot.data[i]; // add scaling later
xScaledValue = i;
RemotePlot.ctx.lineTo(xScaledValue,RemotePlot.data[i]);
i + xScaleFactor;
}
RemotePlot.ctx.stroke();
var deltaTime = new Date().getMilliseconds() - RemotePlot.startTime;
var fps = 1000.0 / deltaTime;
RemotePlot.startTime = new Date().getMilliseconds();
// console.log("fps: " + fps);
RemotePlot.fpsElement.innerHTML = Math.round(fps);
}
}
RemotePlot.initialize();
</script>
</html>
@banderson623
Copy link
Author

(I am sure I could make my JS prettier, but that is not part of this goal)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment