Ethan
Ethan

Reputation: 23

For a graph that draws a sine function in HTML5 canvas, what are all the inputs?

I am attempting to create a simple graphing calculator that draws a sinusoidal functions in canvas.

I found the following code on another Stack Exchange question:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i;

ctx.stroke();

var counter = 0, x=0,y=180;

//100 iterations
var increase = 90/180*Math.PI / 9;
for(i=0; i<=360; i+=10){

     ctx.moveTo(x,y);
    x = i;
    y =  180 - Math.sin(counter) * 120;
    counter += increase;

    ctx.lineTo(x,y);
    ctx.stroke();
    //alert( " x : " + x + " y : " + y + " increase : " + counter ) ;
}

I am trying to figure out which part of the function is the amplitude, phase shift, period, and frequency. I figured out that in the for loop, the values are the phase shift, width of canvas, and the period.

Also, can I change the values of the function by plugging in different values/variables? Can I change the sin to cos or tan just by changing it?

Upvotes: 0

Views: 718

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

I've just added the variables in the existing code. None of them were actual variables, only the 120 for amplitude was already in there.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i;

var counter = 0, x=0, y=180;

var amplitude = 120,
    phase = 180,
    frequency = 2;
// period = 1 / frequency

//100 iterations
var increase = 0.5 * Math.PI / 90;

for(i=0; i<=360; i++) {
    ctx.moveTo(x, y);
    x = i;
    y =  180 - Math.sin((counter + phase) * frequency) * amplitude;
    counter += increase;

    ctx.lineTo(x, y);
    //alert( " x : " + x + " y : " + y + " increase : " + counter ) ;
}
ctx.stroke(); // Don't stroke for each iteration of the loop.
<canvas id="myCanvas" width="500", height="500"></canvas>

Upvotes: 2

Related Questions