![]() Capt. Horatio T.P. Webb |
Parks -- Fall 2013 |
<canvas id="graph1" width="500" height="450" style="border:solid blue 1px;"></canvas>
Here is the code:
var gx = document.getElementById("graph1"); var g = gx.getContext("2d"); g.font="12px Arial"; geth=document.getElementById("graph1").height; getw=document.getElementById("graph1").width; var d=new Array(); var t=new Array(); tick_height=5; pmargin=30; pw=getw-2*pmargin; ph=geth-2*pmargin; // // ** generate the random data // maxy=-1; miny=100000.0 for (i=0;i<50;i++) { t[i]=i+1; d[i]=-1; while (d[i] <= 0) { d[i]=300-6.0*t[i]+parseInt(100.0*Math.random()); } if (d[i] > maxy) maxy=d[i]; if (d[i] < miny) miny=d[i]; } // // *** draw Axis // g.strokeStyle="blue"; g.lineWidth=1; g.beginPath(); g.moveTo( pmargin,(geth-pmargin)); g.lineTo( (pmargin+pw) ,(geth-pmargin) ); g.moveTo( pmargin,(geth-pmargin)); g.lineTo( (pmargin) , pmargin-11 ); // // *** plot data // tstart=pmargin+8; dstart=pmargin+d[0]; g.moveTo(tstart,dstart); for (i=0;i<50;i++) { plotx=tstart+i*8; ploty=pmargin+d[i]; g.lineTo(plotx,ploty); g.fillStyle="red"; g.fillRect(plotx-2,ploty-2,5,5) } g.stroke(); // // *** max, min text // g.strokeText("Max y = "+maxy.toString(),40,50) g.strokeText("Min y = "+miny.toString(),40,70) g.stroke(); // // *** x-axis tick marks and scales // for (tick=0;tick<500;tick=tick+100) { g.moveTo(pmargin+tick,(geth-pmargin)); g.lineTo(pmargin+tick,(geth-pmargin)+tick_height); measureText = g.measureText(tick.toString()); var lshift = measureText.width/2; g.strokeText( tick.toString(),pmargin+tick-lshift,(geth-pmargin)+tick_height+10); } g.stroke(); // // *** y axis tick marks and scales // for (tick=0;tick<500;tick=tick+100) { g.moveTo(pmargin,(geth-pmargin-tick)); g.lineTo(pmargin-5,(geth-pmargin-tick)); measureText = g.measureText(tick.toString()); var lshift = measureText.width; g.strokeText( tick.toString(),pmargin-8-lshift,(geth-pmargin)-tick+4); } g.stroke();