Grafici su java script

Ecco un codice che vi permetterà di disegnare grafici fisici e matematici anche su java script!

Anzi col codice che segue potrete anche far scegliere a chi usa il codice quale dei vari grafici, prima nascosti, mostrare. Ecco un esempio di come potrebbe venire:

 

 

<!DOCTYPE html>
<html>
<style>
body {
background-color: #9fff80;
}
</style>
<h2>GRAFICI!</h2>

<h3>
Scegli un bottone tra questi due e cliccalo

<button type="button" onclick="f1()">Grafico 1</button>
<button type="button" onclick="f2()">Grafico 2</button>
</h3>

<canvas
id="CNV" width="250" height="250" style="border:2px solid
red;background:#ff9933;">
</canvas>

<canvas
id="CNQ" width="250" height="250" style="border:2px solid
red;background:#ff9933;">
</canvas>

<script>
function f1() {

var T=[5,-3,11,-8,2,-10,12,-13,-4,10];
var ctx=CNV.getContext("2d");
var i,h,step=26,pos=0,max=Math.abs(T[0]);
var x0=0,y0=100,L=step*(T.length-1);


for(i=0;i<T.length;i++)

if(Math.abs(T[i])>max)
max=Math.abs(T[i]);
ctx.font="10px Arial";

//----------------tracciamento asse x
ctx.moveTo(x0,y0);ctx.lineTo(x0+CNV.width,y0);
ctx.stroke();

//----------------tracciamento grafico
ctx.moveTo(x0,y0-T[0]*5);
ctx.fillText(T[0],5,y0-T[0]*5);

for(i=1;i<T.length;i++){
ctx.lineTo(pos+step,y0-T[i]*5);
ctx.fillText(T[i],pos+step+5,y0-T[i]*5);
ctx.stroke();
pos=pos+step;

}}
function f2() {
var Q=[-20,1,-4,11,-3,2,-4,15,-17,-3];
var ctx=CNQ.getContext("2d");
var i,h,step=26,pos=0,max=Math.abs(Q[0]);
var x0=0,y0=100,L=step*(Q.length-1);
var sc=(CNQ.height/2-10)/max;
for(i=0;i<Q.length;i++)
if(Math.abs(Q[i])>max)
max=Math.abs(Q[i]);
ctx.font="10px Arial";

//----------------tracciamento asse x
ctx.moveTo(x0,y0);
ctx.lineTo(x0+CNQ.width,y0);
ctx.stroke();

//----------------tracciamento grafico
ctx.moveTo(x0,y0-Q[0]*5);
ctx.fillText(Q[0],5,y0-Q[0]*5);

for(i=1;i<Q.length;i++){
ctx.lineTo(pos+step,y0-Q[i]*5);
ctx.fillText(Q[i],pos+step+5,y0-Q[i]*5);
ctx.stroke();
pos=pos+step;
}
}
</script>
</body>
</html>






Precedente Minuti e secondi vissuti Successivo Javascript: funzioni e multipli