Html5 Graphs In Canvas
I'm new to html5 and trying to display an array of code in a graph. It works for a line graph but for some reason unknown to me not for an exponential one. this my code. My questi
Solution 1:
I had to change width() and height() to width and height a few times (they are simple properties), start the test data at 1 because otherwise the first value is always +infinity", and store data and max instead of generating them multiple times, but now it seems to work.
var data; /* KEEP DATA AS A GLOBAL VARIABLE INSTEAD OF GENERATING IT AGAIN EACH TIME */var graph;
var xPadding = 40;
var yPadding = 40;
functiongenerateTestData5() // generates the array
{
var data = [];
for(var i=1; i<=300; i++){
var sensfi = ((document.getElementById("f5").value)*(document.getElementById("xPos5").value)*(document.getElementById("f5").value))/((i*i*document.getElementById("sDI5").value)/(document.getElementById("rI5").value));
data[i-1] = sensfi;
}
return data;
}
functiongetMaxY5() {
var max = 0;
for(var i = 0; i < data.length; i ++) {
if(data[i] > max) {
max = data[i];
}
}
max += 10 - max % 10;
return max;
}
functiongetXPixel5(val) {
return ((graph.width - 20) / data.length) * val + (20 * 1.5);
}
functiongetYPixel5(val) {
return graph.height - (((graph.height - 20) / getMaxY5()) * val) - 20;
}
functiondraw5(){
data = generateTestData5(); /* USE THE GLOBAL VARIABLE */var max = getMaxY5(); /* STORE MAX INSTEAD OF CHECKING IT MULTIPLE TIMES */
graph = document.getElementById("graph5");
var c = graph.getContext('2d');
c.lineWidth = 2;
c.strokeStyle = '#333';
c.font = 'italic 8pt sans-serif';
c.textAlign = "center";
c.beginPath();
c.moveTo(xPadding, 0);
c.lineTo(xPadding, graph.height - yPadding);
c.lineTo(graph.width, graph.height - yPadding);
c.stroke();
var x = 0;
for(var i = 0; i < data.length + 1; i ++) {
if(x==30) {
c.fillText(i, getXPixel5(i), graph.height - yPadding + 20);
x=0;}
else {
x++;
}
}
c.textAlign = "right";
c.textBaseline = "middle";
for(var i = 0; i < max; i += max/10) {
c.fillText(i, xPadding-10, getYPixel5(i));
}
c.strokeStyle = '#f00';
c.beginPath();
c.moveTo(getXPixel5(0)+10, getYPixel5(data[0])-20);
for(var i = 1; i < data.length + 1; i ++) {
c.lineTo(getXPixel5(i)+10, getYPixel5(data[i])-20);
}
c.stroke();
//c.clearRect(0,0,graph.width,graph.height);
}
draw5();
<form><inputname="f5"id="f5"value=8><inputname="xpos5"id="xPos5"value=100><inputname="sDI5"id="sDI5"value=6.4><inputname="rI5"id="rI5"value=1280></form><canvasid="graph5"width="400"height="300"></canvas>
Post a Comment for "Html5 Graphs In Canvas"